<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>Netty 入门 - 暗夜零星</title><meta name="Description" content="暗夜零星，java程序员。这里是我的个人博客，交流技术，分享经验。"><meta property="og:title" content="Netty 入门" />
<meta property="og:description" content="Netty 入门" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://wlizhi.cc/posts/network/netty02-%E5%85%A5%E9%97%A8/" /><meta property="og:image" content="https://wlizhi.cc/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2024-05-26T09:25:30+08:00" />
<meta property="article:modified_time" content="2024-05-26T09:25:30+08:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://wlizhi.cc/logo.png"/>

<meta name="twitter:title" content="Netty 入门"/>
<meta name="twitter:description" content="Netty 入门"/>
<meta name="application-name" content="暗夜零星">
<meta name="apple-mobile-web-app-title" content="暗夜零星"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://wlizhi.cc/posts/network/netty02-%E5%85%A5%E9%97%A8/" /><link rel="prev" href="https://wlizhi.cc/posts/network/netty01-nio/" /><link rel="next" href="https://wlizhi.cc/posts/network/netty03-%E8%BF%9B%E9%98%B6/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "Netty 入门",
        "inLanguage": "",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/wlizhi.cc\/posts\/network\/netty02-%E5%85%A5%E9%97%A8\/"
        },"genre": "posts","keywords": "网络, Netty","wordcount":  11047 ,
        "url": "https:\/\/wlizhi.cc\/posts\/network\/netty02-%E5%85%A5%E9%97%A8\/","datePublished": "2024-05-26T09:25:30+08:00","dateModified": "2024-05-26T09:25:30+08:00","publisher": {
            "@type": "Organization",
            "name": "Wlizhi"},"author": {
                "@type": "Person",
                "name": "Wlizhi"
            },"description": ""
    }
    </script></head>
    <body header-desktop="fixed" header-mobile="auto"><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="暗夜零星"><span class="header-title-pre"><i class='far fa-moon fa-fw'></i></span>暗夜零星</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 所有文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><a class="menu-item" href="/message-board/"> 留言 </a><a class="menu-item" href="/about/"> 关于 </a><a class="menu-item" href="https://github.com/wlizhi" title="GitHub" rel="noopener noreffer" target="_blank"><i class='fab fa-github fa-fw'></i>  </a><a class="menu-item" href="https://gitee.com/wlizhi" title="Gitee" rel="noopener noreffer" target="_blank"><i class='fab fa-git fa-fw'></i>  </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="点击搜索..." id="search-input-desktop">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="暗夜零星"><span class="header-title-pre"><i class='far fa-moon fa-fw'></i></span>暗夜零星</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="点击搜索..." id="search-input-mobile">
                        <a href="javascript:void(0);" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="javascript:void(0);" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="javascript:void(0);" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">所有文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><a class="menu-item" href="/message-board/" title="">留言</a><a class="menu-item" href="/about/" title="">关于</a><a class="menu-item" href="https://github.com/wlizhi" title="GitHub" rel="noopener noreffer" target="_blank"><i class='fab fa-github fa-fw'></i></a><a class="menu-item" href="https://gitee.com/wlizhi" title="Gitee" rel="noopener noreffer" target="_blank"><i class='fab fa-git fa-fw'></i></a><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                <i class="fas fa-adjust fa-fw"></i>
            </a></div>
    </div>
</header>
<div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div>
<main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">Netty 入门</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="https://wlizhi.cc" title="Author" target="_blank" rel="noopener noreffer author" class="author"><i class="fas fa-user-circle fa-fw"></i>Wlizhi</a></span>&nbsp;<span class="post-category">收录于 <a href="/categories/%E7%BD%91%E7%BB%9C/"><i class="far fa-folder fa-fw"></i>网络</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2024-05-26">2024-05-26</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 11047 字&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 23 分钟&nbsp;<span id="/posts/network/netty02-%E5%85%A5%E9%97%A8/" class="leancloud_visitors" data-flag-title="Netty 入门">
                        <i class="far fa-eye fa-fw"></i>&nbsp;<span class=leancloud-visitors-count></span>&nbsp;次阅读
                    </span>&nbsp;</div>
        </div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>目录</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#1-概述">1. 概述</a>
      <ul>
        <li><a href="#11-netty-是什么">1.1 Netty 是什么？</a></li>
        <li><a href="#12-netty-的作者">1.2 Netty 的作者</a></li>
        <li><a href="#13-netty-的地位">1.3 Netty 的地位</a></li>
        <li><a href="#14-netty-的优势">1.4 Netty 的优势</a></li>
      </ul>
    </li>
    <li><a href="#2-hello-world">2. Hello World</a>
      <ul>
        <li><a href="#21-目标">2.1 目标</a></li>
        <li><a href="#22-服务器端">2.2 服务器端</a></li>
        <li><a href="#23-客户端">2.3 客户端</a></li>
        <li><a href="#24-流程梳理">2.4 流程梳理</a>
          <ul>
            <li><a href="#-提示">💡 提示</a></li>
          </ul>
        </li>
      </ul>
    </li>
    <li><a href="#3-组件">3. 组件</a>
      <ul>
        <li><a href="#31-eventloop">3.1 EventLoop</a>
          <ul>
            <li><a href="#-优雅关闭">💡 优雅关闭</a></li>
            <li><a href="#演示-nioeventloop-处理-io-事件">演示 NioEventLoop 处理 io 事件</a></li>
            <li><a href="#-handler-执行中如何换人">💡 handler 执行中如何换人？</a></li>
            <li><a href="#演示-nioeventloop-处理普通任务">演示 NioEventLoop 处理普通任务</a></li>
            <li><a href="#演示-nioeventloop-处理定时任务">演示 NioEventLoop 处理定时任务</a></li>
          </ul>
        </li>
        <li><a href="#32-channel">3.2 Channel</a>
          <ul>
            <li><a href="#channelfuture">ChannelFuture</a></li>
            <li><a href="#closefuture">CloseFuture</a></li>
            <li><a href="#-异步提升的是什么">💡 异步提升的是什么</a></li>
          </ul>
        </li>
        <li><a href="#33-future--promise">3.3 Future &amp; Promise</a>
          <ul>
            <li><a href="#例1">例1</a></li>
            <li><a href="#例2">例2</a></li>
            <li><a href="#例3">例3</a></li>
            <li><a href="#例4">例4</a></li>
            <li><a href="#例5">例5</a></li>
            <li><a href="#例6">例6</a></li>
          </ul>
        </li>
        <li><a href="#34-handler--pipeline">3.4 Handler &amp; Pipeline</a></li>
        <li><a href="#35-bytebuf">3.5 ByteBuf</a>
          <ul>
            <li><a href="#1创建">1）创建</a></li>
            <li><a href="#2直接内存-vs-堆内存">2）直接内存 vs 堆内存</a></li>
            <li><a href="#3池化-vs-非池化">3）池化 vs 非池化</a></li>
            <li><a href="#4组成">4）组成</a></li>
            <li><a href="#5写入">5）写入</a></li>
            <li><a href="#6扩容">6）扩容</a></li>
            <li><a href="#7读取">7）读取</a></li>
            <li><a href="#8retain--release">8）retain &amp; release</a></li>
            <li><a href="#9slice">9）slice</a></li>
            <li><a href="#10duplicate">10）duplicate</a></li>
            <li><a href="#11copy">11）copy</a></li>
            <li><a href="#12compositebytebuf">12）CompositeByteBuf</a></li>
            <li><a href="#13unpooled">13）Unpooled</a></li>
            <li><a href="#-bytebuf-优势">💡 ByteBuf 优势</a></li>
          </ul>
        </li>
      </ul>
    </li>
    <li><a href="#4-双向通信">4. 双向通信</a>
      <ul>
        <li><a href="#41-练习">4.1 练习</a></li>
        <li><a href="#-读和写的误解">💡 读和写的误解</a></li>
      </ul>
    </li>
  </ul>
</nav></div>
            </div><div class="content" id="content"><p>Netty 入门</p>
<h1 id="二-netty-入门">二. Netty 入门</h1>
<h2 id="1-概述">1. 概述</h2>
<h3 id="11-netty-是什么">1.1 Netty 是什么？</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">Netty is an asynchronous event-driven network application framework
</span></span><span class="line"><span class="cl">for rapid development of maintainable high performance protocol servers &amp; clients.
</span></span></code></pre></td></tr></table>
</div>
</div><p>Netty 是一个异步的、基于事件驱动的网络应用框架，用于快速开发可维护、高性能的网络服务器和客户端</p>
<h3 id="12-netty-的作者">1.2 Netty 的作者</h3>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0005.png"
        data-srcset="/img/0005.png, /img/0005.png 1.5x, /img/0005.png 2x"
        data-sizes="auto"
        alt="/img/0005.png"
        title="/img/0005.png" /></p>
<p>他还是另一个著名网络应用框架 Mina 的重要贡献者</p>
<h3 id="13-netty-的地位">1.3 Netty 的地位</h3>
<p>Netty 在 Java 网络应用框架中的地位就好比：Spring 框架在 JavaEE 开发中的地位</p>
<p>以下的框架都使用了 Netty，因为它们有网络通信需求！</p>
<ul>
<li>Cassandra - nosql 数据库</li>
<li>Spark - 大数据分布式计算框架</li>
<li>Hadoop - 大数据分布式存储框架</li>
<li>RocketMQ - ali 开源的消息队列</li>
<li>ElasticSearch - 搜索引擎</li>
<li>gRPC - rpc 框架</li>
<li>Dubbo - rpc 框架</li>
<li>Spring 5.x - flux api 完全抛弃了 tomcat ，使用 netty 作为服务器端</li>
<li>Zookeeper - 分布式协调框架</li>
</ul>
<h3 id="14-netty-的优势">1.4 Netty 的优势</h3>
<ul>
<li>Netty vs NIO，工作量大，bug 多
<ul>
<li>需要自己构建协议</li>
<li>解决 TCP 传输问题，如粘包、半包</li>
<li>epoll 空轮询导致 CPU 100%</li>
<li>对 API 进行增强，使之更易用，如 FastThreadLocal =&gt; ThreadLocal，ByteBuf =&gt; ByteBuffer</li>
</ul>
</li>
<li>Netty vs 其它网络应用框架
<ul>
<li>Mina 由 apache 维护，将来 3.x 版本可能会有较大重构，破坏 API 向下兼容性，Netty 的开发迭代更迅速，API 更简洁、文档更优秀</li>
<li>久经考验，16年，Netty 版本
<ul>
<li>2.x 2004</li>
<li>3.x 2008</li>
<li>4.x 2013</li>
<li>5.x 已废弃（没有明显的性能提升，维护成本高）</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="2-hello-world">2. Hello World</h2>
<h3 id="21-目标">2.1 目标</h3>
<p>开发一个简单的服务器端和客户端</p>
<ul>
<li>客户端向服务器端发送 hello, world</li>
<li>服务器仅接收，不返回</li>
</ul>
<p>加入依赖</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="line"><span class="cl"><span class="nt">&lt;dependency&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&lt;groupId&gt;</span>io.netty<span class="nt">&lt;/groupId&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&lt;artifactId&gt;</span>netty-all<span class="nt">&lt;/artifactId&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&lt;version&gt;</span>4.1.39.Final<span class="nt">&lt;/version&gt;</span>
</span></span><span class="line"><span class="cl"><span class="nt">&lt;/dependency&gt;</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="22-服务器端">2.2 服务器端</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="k">new</span> <span class="n">ServerBootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">())</span> <span class="c1">// 1
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioServerSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span> <span class="c1">// 2
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="o">.</span><span class="na">childHandler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">NioSocketChannel</span><span class="o">&gt;()</span> <span class="o">{</span> <span class="c1">// 3
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">NioSocketChannel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">StringDecoder</span><span class="o">());</span> <span class="c1">// 5
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">SimpleChannelInboundHandler</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;()</span> <span class="o">{</span> <span class="c1">// 6
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">channelRead0</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">String</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">msg</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">})</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">bind</span><span class="o">(</span><span class="n">8080</span><span class="o">);</span> <span class="c1">// 4
</span></span></span></code></pre></td></tr></table>
</div>
</div><p>代码解读</p>
<ul>
<li>
<p>1 处，创建 NioEventLoopGroup，可以简单理解为 <code>线程池 + Selector</code> 后面会详细展开</p>
</li>
<li>
<p>2 处，选择服务 Scoket 实现类，其中 NioServerSocketChannel 表示基于 NIO 的服务器端实现，其它实现还有</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0006.png"
        data-srcset="/img/0006.png, /img/0006.png 1.5x, /img/0006.png 2x"
        data-sizes="auto"
        alt="/img/0006.png"
        title="/img/0006.png" /></p>
</li>
<li>
<p>3 处，为啥方法叫 childHandler，是接下来添加的处理器都是给 SocketChannel 用的，而不是给 ServerSocketChannel。ChannelInitializer 处理器（仅执行一次），它的作用是待客户端 SocketChannel 建立连接后，执行 initChannel 以便添加更多的处理器</p>
</li>
<li>
<p>4 处，ServerSocketChannel 绑定的监听端口</p>
</li>
<li>
<p>5 处，SocketChannel 的处理器，解码 ByteBuf =&gt; String</p>
</li>
<li>
<p>6 处，SocketChannel 的业务处理器，使用上一个处理器的处理结果</p>
</li>
</ul>
<h3 id="23-客户端">2.3 客户端</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="k">new</span> <span class="n">Bootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">())</span> <span class="c1">// 1
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span> <span class="c1">// 2
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="o">.</span><span class="na">handler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">Channel</span><span class="o">&gt;()</span> <span class="o">{</span> <span class="c1">// 3
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">Channel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">StringEncoder</span><span class="o">());</span> <span class="c1">// 8
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">})</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">connect</span><span class="o">(</span><span class="s">&#34;127.0.0.1&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">)</span> <span class="c1">// 4
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="o">.</span><span class="na">sync</span><span class="o">()</span> <span class="c1">// 5
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="o">.</span><span class="na">channel</span><span class="o">()</span> <span class="c1">// 6
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="o">.</span><span class="na">writeAndFlush</span><span class="o">(</span><span class="k">new</span> <span class="n">Date</span><span class="o">()</span> <span class="o">+</span> <span class="s">&#34;: hello world!&#34;</span><span class="o">);</span> <span class="c1">// 7
</span></span></span></code></pre></td></tr></table>
</div>
</div><p>代码解读</p>
<ul>
<li>
<p>1 处，创建 NioEventLoopGroup，同 Server</p>
</li>
<li>
<p>2 处，选择客户 Socket 实现类，NioSocketChannel 表示基于 NIO 的客户端实现，其它实现还有</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0007.png"
        data-srcset="/img/0007.png, /img/0007.png 1.5x, /img/0007.png 2x"
        data-sizes="auto"
        alt="/img/0007.png"
        title="/img/0007.png" /></p>
</li>
<li>
<p>3 处，添加 SocketChannel 的处理器，ChannelInitializer 处理器（仅执行一次），它的作用是待客户端 SocketChannel 建立连接后，执行 initChannel 以便添加更多的处理器</p>
</li>
<li>
<p>4 处，指定要连接的服务器和端口</p>
</li>
<li>
<p>5 处，Netty 中很多方法都是异步的，如 connect，这时需要使用 sync 方法等待 connect 建立连接完毕</p>
</li>
<li>
<p>6 处，获取 channel 对象，它即为通道抽象，可以进行数据读写操作</p>
</li>
<li>
<p>7 处，写入消息并清空缓冲区</p>
</li>
<li>
<p>8 处，消息会经过通道 handler 处理，这里是将 String =&gt; ByteBuf 发出</p>
</li>
<li>
<p>数据经过网络传输，到达服务器端，服务器端 5 和 6 处的 handler 先后被触发，走完一个流程</p>
</li>
</ul>
<h3 id="24-流程梳理">2.4 流程梳理</h3>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0040.png"
        data-srcset="/img/0040.png, /img/0040.png 1.5x, /img/0040.png 2x"
        data-sizes="auto"
        alt="/img/0040.png"
        title="/img/0040.png" /></p>
<h4 id="-提示">💡 提示</h4>
<blockquote>
<p>一开始需要树立正确的观念</p>
<ul>
<li>把 channel 理解为数据的通道</li>
<li>把 msg 理解为流动的数据，最开始输入是 ByteBuf，但经过 pipeline 的加工，会变成其它类型对象，最后输出又变成 ByteBuf</li>
<li>把 handler 理解为数据的处理工序
<ul>
<li>工序有多道，合在一起就是 pipeline，pipeline 负责发布事件（读、读取完成&hellip;）传播给每个 handler， handler 对自己感兴趣的事件进行处理（重写了相应事件处理方法）</li>
<li>handler 分 Inbound 和 Outbound 两类</li>
</ul>
</li>
<li>把 eventLoop 理解为处理数据的工人
<ul>
<li>工人可以管理多个 channel 的 io 操作，并且一旦工人负责了某个 channel，就要负责到底（绑定）</li>
<li>工人既可以执行 io 操作，也可以进行任务处理，每位工人有任务队列，队列里可以堆放多个 channel 的待处理任务，任务分为普通任务、定时任务</li>
<li>工人按照 pipeline 顺序，依次按照 handler 的规划（代码）处理数据，可以为每道工序指定不同的工人</li>
</ul>
</li>
</ul>
</blockquote>
<h2 id="3-组件">3. 组件</h2>
<h3 id="31-eventloop">3.1 EventLoop</h3>
<p>事件循环对象</p>
<p>EventLoop 本质是一个单线程执行器（同时维护了一个 Selector），里面有 run 方法处理 Channel 上源源不断的 io 事件。</p>
<p>它的继承关系比较复杂</p>
<ul>
<li>一条线是继承自 j.u.c.ScheduledExecutorService 因此包含了线程池中所有的方法</li>
<li>另一条线是继承自 netty 自己的 OrderedEventExecutor，
<ul>
<li>提供了 boolean inEventLoop(Thread thread) 方法判断一个线程是否属于此 EventLoop</li>
<li>提供了 parent 方法来看看自己属于哪个 EventLoopGroup</li>
</ul>
</li>
</ul>
<p>事件循环组</p>
<p>EventLoopGroup 是一组 EventLoop，Channel 一般会调用 EventLoopGroup 的 register 方法来绑定其中一个 EventLoop，后续这个 Channel 上的 io 事件都由此 EventLoop 来处理（保证了 io 事件处理时的线程安全）</p>
<ul>
<li>继承自 netty 自己的 EventExecutorGroup
<ul>
<li>实现了 Iterable 接口提供遍历 EventLoop 的能力</li>
<li>另有 next 方法获取集合中下一个 EventLoop</li>
</ul>
</li>
</ul>
<p>以一个简单的实现为例：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="c1">// 内部创建了两个 EventLoop, 每个 EventLoop 维护一个线程
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">DefaultEventLoopGroup</span> <span class="n">group</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultEventLoopGroup</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">group</span><span class="o">.</span><span class="na">next</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">group</span><span class="o">.</span><span class="na">next</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">group</span><span class="o">.</span><span class="na">next</span><span class="o">());</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">io.netty.channel.DefaultEventLoop@60f82f98
</span></span><span class="line"><span class="cl">io.netty.channel.DefaultEventLoop@35f983a6
</span></span><span class="line"><span class="cl">io.netty.channel.DefaultEventLoop@60f82f98
</span></span></code></pre></td></tr></table>
</div>
</div><p>也可以使用 for 循环</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">DefaultEventLoopGroup</span> <span class="n">group</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultEventLoopGroup</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="k">for</span> <span class="o">(</span><span class="n">EventExecutor</span> <span class="n">eventLoop</span> <span class="o">:</span> <span class="n">group</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">eventLoop</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">io.netty.channel.DefaultEventLoop@60f82f98
</span></span><span class="line"><span class="cl">io.netty.channel.DefaultEventLoop@35f983a6
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="-优雅关闭">💡 优雅关闭</h4>
<p>优雅关闭 <code>shutdownGracefully</code> 方法。该方法会首先切换 <code>EventLoopGroup</code> 到关闭状态从而拒绝新的任务的加入，然后在任务队列的任务都处理完成后，停止线程的运行。从而确保整体应用是在正常有序的状态下退出的</p>
<h4 id="演示-nioeventloop-处理-io-事件">演示 NioEventLoop 处理 io 事件</h4>
<p>服务器端两个 nio worker 工人</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="k">new</span> <span class="n">ServerBootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">(</span><span class="n">1</span><span class="o">),</span> <span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">(</span><span class="n">2</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioServerSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">childHandler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">NioSocketChannel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">NioSocketChannel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInboundHandlerAdapter</span><span class="o">()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">channelRead</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ByteBuf</span> <span class="n">byteBuf</span> <span class="o">=</span> <span class="n">msg</span> <span class="k">instanceof</span> <span class="n">ByteBuf</span> <span class="o">?</span> <span class="o">((</span><span class="n">ByteBuf</span><span class="o">)</span> <span class="n">msg</span><span class="o">)</span> <span class="o">:</span> <span class="kc">null</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">                    <span class="k">if</span> <span class="o">(</span><span class="n">byteBuf</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                        <span class="kt">byte</span><span class="o">[]</span> <span class="n">buf</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">byte</span><span class="o">[</span><span class="n">16</span><span class="o">];</span>
</span></span><span class="line"><span class="cl">                        <span class="n">ByteBuf</span> <span class="n">len</span> <span class="o">=</span> <span class="n">byteBuf</span><span class="o">.</span><span class="na">readBytes</span><span class="o">(</span><span class="n">buf</span><span class="o">,</span> <span class="n">0</span><span class="o">,</span> <span class="n">byteBuf</span><span class="o">.</span><span class="na">readableBytes</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">                        <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="k">new</span> <span class="n">String</span><span class="o">(</span><span class="n">buf</span><span class="o">));</span>
</span></span><span class="line"><span class="cl">                    <span class="o">}</span>
</span></span><span class="line"><span class="cl">                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">}).</span><span class="na">bind</span><span class="o">(</span><span class="n">8080</span><span class="o">).</span><span class="na">sync</span><span class="o">();</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>客户端，启动三次，分别修改发送字符串为 zhangsan（第一次），lisi（第二次），wangwu（第三次）</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">InterruptedException</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">Channel</span> <span class="n">channel</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Bootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">            <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">(</span><span class="n">1</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">            <span class="o">.</span><span class="na">handler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">NioSocketChannel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">NioSocketChannel</span> <span class="n">ch</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;init...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">LoggingHandler</span><span class="o">(</span><span class="n">LogLevel</span><span class="o">.</span><span class="na">DEBUG</span><span class="o">));</span>
</span></span><span class="line"><span class="cl">                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">})</span>
</span></span><span class="line"><span class="cl">            <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">).</span><span class="na">connect</span><span class="o">(</span><span class="s">&#34;localhost&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">            <span class="o">.</span><span class="na">sync</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">            <span class="o">.</span><span class="na">channel</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">channel</span><span class="o">.</span><span class="na">writeAndFlush</span><span class="o">(</span><span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">buffer</span><span class="o">().</span><span class="na">writeBytes</span><span class="o">(</span><span class="s">&#34;wangwu&#34;</span><span class="o">.</span><span class="na">getBytes</span><span class="o">()));</span>
</span></span><span class="line"><span class="cl">    <span class="n">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="n">2000</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="n">channel</span><span class="o">.</span><span class="na">writeAndFlush</span><span class="o">(</span><span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">buffer</span><span class="o">().</span><span class="na">writeBytes</span><span class="o">(</span><span class="s">&#34;wangwu&#34;</span><span class="o">.</span><span class="na">getBytes</span><span class="o">()));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>最后输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">22:03:34 [DEBUG] [nioEventLoopGroup-3-1] c.i.o.EventLoopTest - zhangsan       
</span></span><span class="line"><span class="cl">22:03:36 [DEBUG] [nioEventLoopGroup-3-1] c.i.o.EventLoopTest - zhangsan       
</span></span><span class="line"><span class="cl">22:05:36 [DEBUG] [nioEventLoopGroup-3-2] c.i.o.EventLoopTest - lisi           
</span></span><span class="line"><span class="cl">22:05:38 [DEBUG] [nioEventLoopGroup-3-2] c.i.o.EventLoopTest - lisi           
</span></span><span class="line"><span class="cl">22:06:09 [DEBUG] [nioEventLoopGroup-3-1] c.i.o.EventLoopTest - wangwu        
</span></span><span class="line"><span class="cl">22:06:11 [DEBUG] [nioEventLoopGroup-3-1] c.i.o.EventLoopTest - wangwu         
</span></span></code></pre></td></tr></table>
</div>
</div><p>可以看到两个工人轮流处理 channel，但工人与 channel 之间进行了绑定</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0042.png"
        data-srcset="/img/0042.png, /img/0042.png 1.5x, /img/0042.png 2x"
        data-sizes="auto"
        alt="/img/0042.png"
        title="/img/0042.png" /></p>
<p>再增加两个非 nio 工人</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">DefaultEventLoopGroup</span> <span class="n">normalWorkers</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultEventLoopGroup</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="k">new</span> <span class="n">ServerBootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">(</span><span class="n">1</span><span class="o">),</span> <span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">(</span><span class="n">2</span><span class="o">))</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioServerSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">childHandler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">NioSocketChannel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">NioSocketChannel</span> <span class="n">ch</span><span class="o">)</span>  <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">LoggingHandler</span><span class="o">(</span><span class="n">LogLevel</span><span class="o">.</span><span class="na">DEBUG</span><span class="o">));</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="n">normalWorkers</span><span class="o">,</span><span class="s">&#34;myhandler&#34;</span><span class="o">,</span>
</span></span><span class="line"><span class="cl">              <span class="k">new</span> <span class="n">ChannelInboundHandlerAdapter</span><span class="o">()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">channelRead</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ByteBuf</span> <span class="n">byteBuf</span> <span class="o">=</span> <span class="n">msg</span> <span class="k">instanceof</span> <span class="n">ByteBuf</span> <span class="o">?</span> <span class="o">((</span><span class="n">ByteBuf</span><span class="o">)</span> <span class="n">msg</span><span class="o">)</span> <span class="o">:</span> <span class="kc">null</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">                    <span class="k">if</span> <span class="o">(</span><span class="n">byteBuf</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                        <span class="kt">byte</span><span class="o">[]</span> <span class="n">buf</span> <span class="o">=</span> <span class="k">new</span> <span class="kt">byte</span><span class="o">[</span><span class="n">16</span><span class="o">];</span>
</span></span><span class="line"><span class="cl">                        <span class="n">ByteBuf</span> <span class="n">len</span> <span class="o">=</span> <span class="n">byteBuf</span><span class="o">.</span><span class="na">readBytes</span><span class="o">(</span><span class="n">buf</span><span class="o">,</span> <span class="n">0</span><span class="o">,</span> <span class="n">byteBuf</span><span class="o">.</span><span class="na">readableBytes</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">                        <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="k">new</span> <span class="n">String</span><span class="o">(</span><span class="n">buf</span><span class="o">));</span>
</span></span><span class="line"><span class="cl">                    <span class="o">}</span>
</span></span><span class="line"><span class="cl">                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">}).</span><span class="na">bind</span><span class="o">(</span><span class="n">8080</span><span class="o">).</span><span class="na">sync</span><span class="o">();</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>客户端代码不变，启动三次，分别修改发送字符串为 zhangsan（第一次），lisi（第二次），wangwu（第三次）</p>
<p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">22:19:48 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x251562d5, L:/127.0.0.1:8080 - R:/127.0.0.1:52588] REGISTERED
</span></span><span class="line"><span class="cl">22:19:48 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x251562d5, L:/127.0.0.1:8080 - R:/127.0.0.1:52588] ACTIVE
</span></span><span class="line"><span class="cl">22:19:48 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x251562d5, L:/127.0.0.1:8080 - R:/127.0.0.1:52588] READ: 8B
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 7a 68 61 6e 67 73 61 6e                         |zhangsan        |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">22:19:48 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x251562d5, L:/127.0.0.1:8080 - R:/127.0.0.1:52588] READ COMPLETE
</span></span><span class="line"><span class="cl">22:19:48 [DEBUG] [defaultEventLoopGroup-2-1] c.i.o.EventLoopTest - zhangsan        
</span></span><span class="line"><span class="cl">22:19:50 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x251562d5, L:/127.0.0.1:8080 - R:/127.0.0.1:52588] READ: 8B
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 7a 68 61 6e 67 73 61 6e                         |zhangsan        |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">22:19:50 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x251562d5, L:/127.0.0.1:8080 - R:/127.0.0.1:52588] READ COMPLETE
</span></span><span class="line"><span class="cl">22:19:50 [DEBUG] [defaultEventLoopGroup-2-1] c.i.o.EventLoopTest - zhangsan        
</span></span><span class="line"><span class="cl">22:20:24 [DEBUG] [nioEventLoopGroup-4-2] i.n.h.l.LoggingHandler - [id: 0x94b2a840, L:/127.0.0.1:8080 - R:/127.0.0.1:52612] REGISTERED
</span></span><span class="line"><span class="cl">22:20:24 [DEBUG] [nioEventLoopGroup-4-2] i.n.h.l.LoggingHandler - [id: 0x94b2a840, L:/127.0.0.1:8080 - R:/127.0.0.1:52612] ACTIVE
</span></span><span class="line"><span class="cl">22:20:25 [DEBUG] [nioEventLoopGroup-4-2] i.n.h.l.LoggingHandler - [id: 0x94b2a840, L:/127.0.0.1:8080 - R:/127.0.0.1:52612] READ: 4B
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 6c 69 73 69                                     |lisi            |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">22:20:25 [DEBUG] [nioEventLoopGroup-4-2] i.n.h.l.LoggingHandler - [id: 0x94b2a840, L:/127.0.0.1:8080 - R:/127.0.0.1:52612] READ COMPLETE
</span></span><span class="line"><span class="cl">22:20:25 [DEBUG] [defaultEventLoopGroup-2-2] c.i.o.EventLoopTest - lisi            
</span></span><span class="line"><span class="cl">22:20:27 [DEBUG] [nioEventLoopGroup-4-2] i.n.h.l.LoggingHandler - [id: 0x94b2a840, L:/127.0.0.1:8080 - R:/127.0.0.1:52612] READ: 4B
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 6c 69 73 69                                     |lisi            |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">22:20:27 [DEBUG] [nioEventLoopGroup-4-2] i.n.h.l.LoggingHandler - [id: 0x94b2a840, L:/127.0.0.1:8080 - R:/127.0.0.1:52612] READ COMPLETE
</span></span><span class="line"><span class="cl">22:20:27 [DEBUG] [defaultEventLoopGroup-2-2] c.i.o.EventLoopTest - lisi            
</span></span><span class="line"><span class="cl">22:20:38 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x79a26af9, L:/127.0.0.1:8080 - R:/127.0.0.1:52625] REGISTERED
</span></span><span class="line"><span class="cl">22:20:38 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x79a26af9, L:/127.0.0.1:8080 - R:/127.0.0.1:52625] ACTIVE
</span></span><span class="line"><span class="cl">22:20:38 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x79a26af9, L:/127.0.0.1:8080 - R:/127.0.0.1:52625] READ: 6B
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 77 61 6e 67 77 75                               |wangwu          |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">22:20:38 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x79a26af9, L:/127.0.0.1:8080 - R:/127.0.0.1:52625] READ COMPLETE
</span></span><span class="line"><span class="cl">22:20:38 [DEBUG] [defaultEventLoopGroup-2-1] c.i.o.EventLoopTest - wangwu          
</span></span><span class="line"><span class="cl">22:20:40 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x79a26af9, L:/127.0.0.1:8080 - R:/127.0.0.1:52625] READ: 6B
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 77 61 6e 67 77 75                               |wangwu          |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">22:20:40 [DEBUG] [nioEventLoopGroup-4-1] i.n.h.l.LoggingHandler - [id: 0x79a26af9, L:/127.0.0.1:8080 - R:/127.0.0.1:52625] READ COMPLETE
</span></span><span class="line"><span class="cl">22:20:40 [DEBUG] [defaultEventLoopGroup-2-1] c.i.o.EventLoopTest - wangwu          
</span></span></code></pre></td></tr></table>
</div>
</div><p>可以看到，nio 工人和 非 nio 工人也分别绑定了 channel（LoggingHandler 由 nio 工人执行，而我们自己的 handler 由非 nio 工人执行）</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0041.png"
        data-srcset="/img/0041.png, /img/0041.png 1.5x, /img/0041.png 2x"
        data-sizes="auto"
        alt="/img/0041.png"
        title="/img/0041.png" /></p>
<h4 id="-handler-执行中如何换人">💡 handler 执行中如何换人？</h4>
<p>关键代码 <code>io.netty.channel.AbstractChannelHandlerContext#invokeChannelRead()</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">static</span> <span class="kt">void</span> <span class="nf">invokeChannelRead</span><span class="o">(</span><span class="kd">final</span> <span class="n">AbstractChannelHandlerContext</span> <span class="n">next</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="kd">final</span> <span class="n">Object</span> <span class="n">m</span> <span class="o">=</span> <span class="n">next</span><span class="o">.</span><span class="na">pipeline</span><span class="o">.</span><span class="na">touch</span><span class="o">(</span><span class="n">ObjectUtil</span><span class="o">.</span><span class="na">checkNotNull</span><span class="o">(</span><span class="n">msg</span><span class="o">,</span> <span class="s">&#34;msg&#34;</span><span class="o">),</span> <span class="n">next</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// 下一个 handler 的事件循环是否与当前的事件循环是同一个线程
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="n">EventExecutor</span> <span class="n">executor</span> <span class="o">=</span> <span class="n">next</span><span class="o">.</span><span class="na">executor</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    
</span></span><span class="line"><span class="cl">    <span class="c1">// 是，直接调用
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="k">if</span> <span class="o">(</span><span class="n">executor</span><span class="o">.</span><span class="na">inEventLoop</span><span class="o">())</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">next</span><span class="o">.</span><span class="na">invokeChannelRead</span><span class="o">(</span><span class="n">m</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span> 
</span></span><span class="line"><span class="cl">    <span class="c1">// 不是，将要执行的代码作为任务提交给下一个事件循环处理（换人）
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="k">else</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">executor</span><span class="o">.</span><span class="na">execute</span><span class="o">(</span><span class="k">new</span> <span class="n">Runnable</span><span class="o">()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">            <span class="kd">public</span> <span class="kt">void</span> <span class="nf">run</span><span class="o">()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">next</span><span class="o">.</span><span class="na">invokeChannelRead</span><span class="o">(</span><span class="n">m</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span>
</span></span><span class="line"><span class="cl">        <span class="o">});</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>如果两个 handler 绑定的是同一个线程，那么就直接调用</li>
<li>否则，把要调用的代码封装为一个任务对象，由下一个 handler 的线程来调用</li>
</ul>
<h4 id="演示-nioeventloop-处理普通任务">演示 NioEventLoop 处理普通任务</h4>
<p>NioEventLoop 除了可以处理 io 事件，同样可以向它提交普通任务</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">NioEventLoopGroup</span> <span class="n">nioWorkers</span> <span class="o">=</span> <span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;server start...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="n">2000</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">nioWorkers</span><span class="o">.</span><span class="na">execute</span><span class="o">(()-&gt;{</span>
</span></span><span class="line"><span class="cl">    <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;normal task...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">22:30:36 [DEBUG] [main] c.i.o.EventLoopTest2 - server start...
</span></span><span class="line"><span class="cl">22:30:38 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - normal task...
</span></span></code></pre></td></tr></table>
</div>
</div><blockquote>
<p>可以用来执行耗时较长的任务</p>
</blockquote>
<h4 id="演示-nioeventloop-处理定时任务">演示 NioEventLoop 处理定时任务</h4>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">NioEventLoopGroup</span> <span class="n">nioWorkers</span> <span class="o">=</span> <span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;server start...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="n">2000</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">nioWorkers</span><span class="o">.</span><span class="na">scheduleAtFixedRate</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;running...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="o">},</span> <span class="n">0</span><span class="o">,</span> <span class="n">1</span><span class="o">,</span> <span class="n">TimeUnit</span><span class="o">.</span><span class="na">SECONDS</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">22:35:15 [DEBUG] [main] c.i.o.EventLoopTest2 - server start...
</span></span><span class="line"><span class="cl">22:35:17 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - running...
</span></span><span class="line"><span class="cl">22:35:18 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - running...
</span></span><span class="line"><span class="cl">22:35:19 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - running...
</span></span><span class="line"><span class="cl">22:35:20 [DEBUG] [nioEventLoopGroup-2-1] c.i.o.EventLoopTest2 - running...
</span></span><span class="line"><span class="cl">...
</span></span></code></pre></td></tr></table>
</div>
</div><blockquote>
<p>可以用来执行定时任务</p>
</blockquote>
<h3 id="32-channel">3.2 Channel</h3>
<p>channel 的主要作用</p>
<ul>
<li>close() 可以用来关闭 channel</li>
<li>closeFuture() 用来处理 channel 的关闭
<ul>
<li>sync 方法作用是同步等待 channel 关闭</li>
<li>而 addListener 方法是异步等待 channel 关闭</li>
</ul>
</li>
<li>pipeline() 方法添加处理器</li>
<li>write() 方法将数据写入</li>
<li>writeAndFlush() 方法将数据写入并刷出</li>
</ul>
<h4 id="channelfuture">ChannelFuture</h4>
<p>这时刚才的客户端代码</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="k">new</span> <span class="n">Bootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">handler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">Channel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">Channel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">StringEncoder</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">})</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">connect</span><span class="o">(</span><span class="s">&#34;127.0.0.1&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">sync</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">writeAndFlush</span><span class="o">(</span><span class="k">new</span> <span class="n">Date</span><span class="o">()</span> <span class="o">+</span> <span class="s">&#34;: hello world!&#34;</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>现在把它拆开来看</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ChannelFuture</span> <span class="n">channelFuture</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Bootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">handler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">Channel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">Channel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">StringEncoder</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">})</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">connect</span><span class="o">(</span><span class="s">&#34;127.0.0.1&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">);</span> <span class="c1">// 1
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>
</span></span><span class="line"><span class="cl"><span class="n">channelFuture</span><span class="o">.</span><span class="na">sync</span><span class="o">().</span><span class="na">channel</span><span class="o">().</span><span class="na">writeAndFlush</span><span class="o">(</span><span class="k">new</span> <span class="n">Date</span><span class="o">()</span> <span class="o">+</span> <span class="s">&#34;: hello world!&#34;</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>1 处返回的是 ChannelFuture 对象，它的作用是利用 channel() 方法来获取 Channel 对象</li>
</ul>
<p><strong>注意</strong> connect 方法是异步的，意味着不等连接建立，方法执行就返回了。因此 channelFuture 对象中不能【立刻】获得到正确的 Channel 对象</p>
<p>实验如下：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ChannelFuture</span> <span class="n">channelFuture</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Bootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">handler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">Channel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">Channel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">StringEncoder</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">})</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">connect</span><span class="o">(</span><span class="s">&#34;127.0.0.1&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">channelFuture</span><span class="o">.</span><span class="na">channel</span><span class="o">());</span> <span class="c1">// 1
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">channelFuture</span><span class="o">.</span><span class="na">sync</span><span class="o">();</span> <span class="c1">// 2
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">channelFuture</span><span class="o">.</span><span class="na">channel</span><span class="o">());</span> <span class="c1">// 3
</span></span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>执行到 1 时，连接未建立，打印 <code>[id: 0x2e1884dd]</code></li>
<li>执行到 2 时，sync 方法是同步等待连接建立完成</li>
<li>执行到 3 时，连接肯定建立了，打印 <code>[id: 0x2e1884dd, L:/127.0.0.1:57191 - R:/127.0.0.1:8080]</code></li>
</ul>
<p>除了用 sync 方法可以让异步操作同步以外，还可以使用回调的方式：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ChannelFuture</span> <span class="n">channelFuture</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Bootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">handler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">Channel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">Channel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">StringEncoder</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">})</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">connect</span><span class="o">(</span><span class="s">&#34;127.0.0.1&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">channelFuture</span><span class="o">.</span><span class="na">channel</span><span class="o">());</span> <span class="c1">// 1
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">channelFuture</span><span class="o">.</span><span class="na">addListener</span><span class="o">((</span><span class="n">ChannelFutureListener</span><span class="o">)</span> <span class="n">future</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">future</span><span class="o">.</span><span class="na">channel</span><span class="o">());</span> <span class="c1">// 2
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="o">});</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>执行到 1 时，连接未建立，打印 <code>[id: 0x749124ba]</code></li>
<li>ChannelFutureListener 会在连接建立时被调用（其中 operationComplete 方法），因此执行到 2 时，连接肯定建立了，打印 <code>[id: 0x749124ba, L:/127.0.0.1:57351 - R:/127.0.0.1:8080]</code></li>
</ul>
<h4 id="closefuture">CloseFuture</h4>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="nd">@Slf4j</span>
</span></span><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">CloseFutureClient</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">InterruptedException</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">NioEventLoopGroup</span> <span class="n">group</span> <span class="k">new</span> <span class="nf">NioEventLoopGroup</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">        <span class="n">ChannelFuture</span> <span class="n">channelFuture</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Bootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">                <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="n">group</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">                <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">                <span class="o">.</span><span class="na">handler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">NioSocketChannel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="nd">@Override</span> <span class="c1">// 在连接建立后被调用
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                    <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">NioSocketChannel</span> <span class="n">ch</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                        <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">LoggingHandler</span><span class="o">(</span><span class="n">LogLevel</span><span class="o">.</span><span class="na">DEBUG</span><span class="o">));</span>
</span></span><span class="line"><span class="cl">                        <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">StringEncoder</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">                    <span class="o">}</span>
</span></span><span class="line"><span class="cl">                <span class="o">})</span>
</span></span><span class="line"><span class="cl">                <span class="o">.</span><span class="na">connect</span><span class="o">(</span><span class="k">new</span> <span class="n">InetSocketAddress</span><span class="o">(</span><span class="s">&#34;localhost&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">));</span>
</span></span><span class="line"><span class="cl">        <span class="n">Channel</span> <span class="n">channel</span> <span class="o">=</span> <span class="n">channelFuture</span><span class="o">.</span><span class="na">sync</span><span class="o">().</span><span class="na">channel</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">        <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;{}&#34;</span><span class="o">,</span> <span class="n">channel</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">        <span class="k">new</span> <span class="n">Thread</span><span class="o">(()-&gt;{</span>
</span></span><span class="line"><span class="cl">            <span class="n">Scanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Scanner</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">in</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">            <span class="k">while</span> <span class="o">(</span><span class="kc">true</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">String</span> <span class="n">line</span> <span class="o">=</span> <span class="n">scanner</span><span class="o">.</span><span class="na">nextLine</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">                <span class="k">if</span> <span class="o">(</span><span class="s">&#34;q&#34;</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">line</span><span class="o">))</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">channel</span><span class="o">.</span><span class="na">close</span><span class="o">();</span> <span class="c1">// close 异步操作 1s 之后
</span></span></span><span class="line"><span class="cl"><span class="c1">//                    log.debug(&#34;处理关闭之后的操作&#34;); // 不能在这里善后
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                    <span class="k">break</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">                <span class="o">}</span>
</span></span><span class="line"><span class="cl">                <span class="n">channel</span><span class="o">.</span><span class="na">writeAndFlush</span><span class="o">(</span><span class="n">line</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span>
</span></span><span class="line"><span class="cl">        <span class="o">},</span> <span class="s">&#34;input&#34;</span><span class="o">).</span><span class="na">start</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="c1">// 获取 CloseFuture 对象， 1) 同步处理关闭， 2) 异步处理关闭
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>        <span class="n">ChannelFuture</span> <span class="n">closeFuture</span> <span class="o">=</span> <span class="n">channel</span><span class="o">.</span><span class="na">closeFuture</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">        <span class="cm">/*log.debug(&#34;waiting close...&#34;);
</span></span></span><span class="line"><span class="cl"><span class="cm">        closeFuture.sync();
</span></span></span><span class="line"><span class="cl"><span class="cm">        log.debug(&#34;处理关闭之后的操作&#34;);*/</span>
</span></span><span class="line"><span class="cl">        <span class="n">closeFuture</span><span class="o">.</span><span class="na">addListener</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelFutureListener</span><span class="o">()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">            <span class="kd">public</span> <span class="kt">void</span> <span class="nf">operationComplete</span><span class="o">(</span><span class="n">ChannelFuture</span> <span class="n">future</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;处理关闭之后的操作&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                <span class="n">group</span><span class="o">.</span><span class="na">shutdownGracefully</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span>
</span></span><span class="line"><span class="cl">        <span class="o">});</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="-异步提升的是什么">💡 异步提升的是什么</h4>
<ul>
<li>
<p>有些同学看到这里会有疑问：为什么不在一个线程中去执行建立连接、去执行关闭 channel，那样不是也可以吗？非要用这么复杂的异步方式：比如一个线程发起建立连接，另一个线程去真正建立连接</p>
</li>
<li>
<p>还有同学会笼统地回答，因为 netty 异步方式用了多线程、多线程就效率高。其实这些认识都比较片面，多线程和异步所提升的效率并不是所认为的</p>
</li>
</ul>
<p>思考下面的场景，4 个医生给人看病，每个病人花费 20 分钟，而且医生看病的过程中是以病人为单位的，一个病人看完了，才能看下一个病人。假设病人源源不断地来，可以计算一下 4 个医生一天工作 8 小时，处理的病人总数是：<code>4 * 8 * 3 = 96</code></p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0044.png"
        data-srcset="/img/0044.png, /img/0044.png 1.5x, /img/0044.png 2x"
        data-sizes="auto"
        alt="/img/0044.png"
        title="/img/0044.png" /></p>
<p>经研究发现，看病可以细分为四个步骤，经拆分后每个步骤需要 5 分钟，如下</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0048.png"
        data-srcset="/img/0048.png, /img/0048.png 1.5x, /img/0048.png 2x"
        data-sizes="auto"
        alt="/img/0048.png"
        title="/img/0048.png" /></p>
<p>因此可以做如下优化，只有一开始，医生 2、3、4 分别要等待 5、10、15 分钟才能执行工作，但只要后续病人源源不断地来，他们就能够满负荷工作，并且处理病人的能力提高到了 <code>4 * 8 * 12</code> 效率几乎是原来的四倍</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0047.png"
        data-srcset="/img/0047.png, /img/0047.png 1.5x, /img/0047.png 2x"
        data-sizes="auto"
        alt="/img/0047.png"
        title="/img/0047.png" /></p>
<p>要点</p>
<ul>
<li>单线程没法异步提高效率，必须配合多线程、多核 cpu 才能发挥异步的优势</li>
<li>异步并没有缩短响应时间，反而有所增加</li>
<li>合理进行任务拆分，也是利用异步的关键</li>
</ul>
<h3 id="33-future--promise">3.3 Future &amp; Promise</h3>
<p>在异步处理时，经常用到这两个接口</p>
<p>首先要说明 netty 中的 Future 与 jdk 中的 Future 同名，但是是两个接口，netty 的 Future 继承自 jdk 的 Future，而 Promise 又对 netty Future 进行了扩展</p>
<ul>
<li>jdk Future 只能同步等待任务结束（或成功、或失败）才能得到结果</li>
<li>netty Future 可以同步等待任务结束得到结果，也可以异步方式得到结果，但都是要等任务结束</li>
<li>netty Promise 不仅有 netty Future 的功能，而且脱离了任务独立存在，只作为两个线程间传递结果的容器</li>
</ul>
<table>
<thead>
<tr>
<th>功能/名称</th>
<th>jdk Future</th>
<th>netty Future</th>
<th>Promise</th>
</tr>
</thead>
<tbody>
<tr>
<td>cancel</td>
<td>取消任务</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>isCanceled</td>
<td>任务是否取消</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>isDone</td>
<td>任务是否完成，不能区分成功失败</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>get</td>
<td>获取任务结果，阻塞等待</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>getNow</td>
<td>-</td>
<td>获取任务结果，非阻塞，还未产生结果时返回 null</td>
<td>-</td>
</tr>
<tr>
<td>await</td>
<td>-</td>
<td>等待任务结束，如果任务失败，不会抛异常，而是通过 isSuccess 判断</td>
<td>-</td>
</tr>
<tr>
<td>sync</td>
<td>-</td>
<td>等待任务结束，如果任务失败，抛出异常</td>
<td>-</td>
</tr>
<tr>
<td>isSuccess</td>
<td>-</td>
<td>判断任务是否成功</td>
<td>-</td>
</tr>
<tr>
<td>cause</td>
<td>-</td>
<td>获取失败信息，非阻塞，如果没有失败，返回null</td>
<td>-</td>
</tr>
<tr>
<td>addLinstener</td>
<td>-</td>
<td>添加回调，异步接收结果</td>
<td>-</td>
</tr>
<tr>
<td>setSuccess</td>
<td>-</td>
<td>-</td>
<td>设置成功结果</td>
</tr>
<tr>
<td>setFailure</td>
<td>-</td>
<td>-</td>
<td>设置失败结果</td>
</tr>
</tbody>
</table>
<h4 id="例1">例1</h4>
<p>同步处理任务成功</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">DefaultEventLoop</span> <span class="n">eventExecutors</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultEventLoop</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">DefaultPromise</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">promise</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultPromise</span><span class="o">&lt;&gt;(</span><span class="n">eventExecutors</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">eventExecutors</span><span class="o">.</span><span class="na">execute</span><span class="o">(()-&gt;{</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="n">1000</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">InterruptedException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;set success, {}&#34;</span><span class="o">,</span><span class="n">10</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="n">promise</span><span class="o">.</span><span class="na">setSuccess</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;start...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;{}&#34;</span><span class="o">,</span><span class="n">promise</span><span class="o">.</span><span class="na">getNow</span><span class="o">());</span> <span class="c1">// 还没有结果
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;{}&#34;</span><span class="o">,</span><span class="n">promise</span><span class="o">.</span><span class="na">get</span><span class="o">());</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">11:51:53 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - start...
</span></span><span class="line"><span class="cl">11:51:53 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - null
</span></span><span class="line"><span class="cl">11:51:54 [DEBUG] [defaultEventLoop-1-1] c.i.o.DefaultPromiseTest2 - set success, 10
</span></span><span class="line"><span class="cl">11:51:54 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - 10
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="例2">例2</h4>
<p>异步处理任务成功</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">DefaultEventLoop</span> <span class="n">eventExecutors</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultEventLoop</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">DefaultPromise</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">promise</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultPromise</span><span class="o">&lt;&gt;(</span><span class="n">eventExecutors</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 设置回调，异步接收结果
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">promise</span><span class="o">.</span><span class="na">addListener</span><span class="o">(</span><span class="n">future</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// 这里的 future 就是上面的 promise
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;{}&#34;</span><span class="o">,</span><span class="n">future</span><span class="o">.</span><span class="na">getNow</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 等待 1000 后设置成功结果
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">eventExecutors</span><span class="o">.</span><span class="na">execute</span><span class="o">(()-&gt;{</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="n">1000</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">InterruptedException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;set success, {}&#34;</span><span class="o">,</span><span class="n">10</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="n">promise</span><span class="o">.</span><span class="na">setSuccess</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;start...&#34;</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">11:49:30 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - start...
</span></span><span class="line"><span class="cl">11:49:31 [DEBUG] [defaultEventLoop-1-1] c.i.o.DefaultPromiseTest2 - set success, 10
</span></span><span class="line"><span class="cl">11:49:31 [DEBUG] [defaultEventLoop-1-1] c.i.o.DefaultPromiseTest2 - 10
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="例3">例3</h4>
<p>同步处理任务失败 - sync &amp; get</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">DefaultEventLoop</span> <span class="n">eventExecutors</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultEventLoop</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">        <span class="n">DefaultPromise</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">promise</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultPromise</span><span class="o">&lt;&gt;(</span><span class="n">eventExecutors</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="n">eventExecutors</span><span class="o">.</span><span class="na">execute</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="n">1000</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">InterruptedException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="n">RuntimeException</span> <span class="n">e</span> <span class="o">=</span> <span class="k">new</span> <span class="n">RuntimeException</span><span class="o">(</span><span class="s">&#34;error...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">            <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;set failure, {}&#34;</span><span class="o">,</span> <span class="n">e</span><span class="o">.</span><span class="na">toString</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">            <span class="n">promise</span><span class="o">.</span><span class="na">setFailure</span><span class="o">(</span><span class="n">e</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">        <span class="o">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;start...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">        <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;{}&#34;</span><span class="o">,</span> <span class="n">promise</span><span class="o">.</span><span class="na">getNow</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">        <span class="n">promise</span><span class="o">.</span><span class="na">get</span><span class="o">();</span> <span class="c1">// sync() 也会出现异常，只是 get 会再用 ExecutionException 包一层异常
</span></span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">12:11:07 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - start...
</span></span><span class="line"><span class="cl">12:11:07 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - null
</span></span><span class="line"><span class="cl">12:11:08 [DEBUG] [defaultEventLoop-1-1] c.i.o.DefaultPromiseTest2 - set failure, java.lang.RuntimeException: error...
</span></span><span class="line"><span class="cl">Exception in thread &#34;main&#34; java.util.concurrent.ExecutionException: java.lang.RuntimeException: error...
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.AbstractFuture.get(AbstractFuture.java:41)
</span></span><span class="line"><span class="cl">	at com.itcast.oio.DefaultPromiseTest2.main(DefaultPromiseTest2.java:34)
</span></span><span class="line"><span class="cl">Caused by: java.lang.RuntimeException: error...
</span></span><span class="line"><span class="cl">	at com.itcast.oio.DefaultPromiseTest2.lambda$main$0(DefaultPromiseTest2.java:27)
</span></span><span class="line"><span class="cl">	at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:918)
</span></span><span class="line"><span class="cl">	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
</span></span><span class="line"><span class="cl">	at java.lang.Thread.run(Thread.java:745)
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="例4">例4</h4>
<p>同步处理任务失败 - await</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">DefaultEventLoop</span> <span class="n">eventExecutors</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultEventLoop</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">DefaultPromise</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">promise</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultPromise</span><span class="o">&lt;&gt;(</span><span class="n">eventExecutors</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">eventExecutors</span><span class="o">.</span><span class="na">execute</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="n">1000</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">InterruptedException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="n">RuntimeException</span> <span class="n">e</span> <span class="o">=</span> <span class="k">new</span> <span class="n">RuntimeException</span><span class="o">(</span><span class="s">&#34;error...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;set failure, {}&#34;</span><span class="o">,</span> <span class="n">e</span><span class="o">.</span><span class="na">toString</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">    <span class="n">promise</span><span class="o">.</span><span class="na">setFailure</span><span class="o">(</span><span class="n">e</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;start...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;{}&#34;</span><span class="o">,</span> <span class="n">promise</span><span class="o">.</span><span class="na">getNow</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">promise</span><span class="o">.</span><span class="na">await</span><span class="o">();</span> <span class="c1">// 与 sync 和 get 区别在于，不会抛异常
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;result {}&#34;</span><span class="o">,</span> <span class="o">(</span><span class="n">promise</span><span class="o">.</span><span class="na">isSuccess</span><span class="o">()</span> <span class="o">?</span> <span class="n">promise</span><span class="o">.</span><span class="na">getNow</span><span class="o">()</span> <span class="o">:</span> <span class="n">promise</span><span class="o">.</span><span class="na">cause</span><span class="o">()).</span><span class="na">toString</span><span class="o">());</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">12:18:53 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - start...
</span></span><span class="line"><span class="cl">12:18:53 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - null
</span></span><span class="line"><span class="cl">12:18:54 [DEBUG] [defaultEventLoop-1-1] c.i.o.DefaultPromiseTest2 - set failure, java.lang.RuntimeException: error...
</span></span><span class="line"><span class="cl">12:18:54 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - result java.lang.RuntimeException: error...
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="例5">例5</h4>
<p>异步处理任务失败</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">DefaultEventLoop</span> <span class="n">eventExecutors</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultEventLoop</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">DefaultPromise</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">promise</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultPromise</span><span class="o">&lt;&gt;(</span><span class="n">eventExecutors</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">promise</span><span class="o">.</span><span class="na">addListener</span><span class="o">(</span><span class="n">future</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;result {}&#34;</span><span class="o">,</span> <span class="o">(</span><span class="n">promise</span><span class="o">.</span><span class="na">isSuccess</span><span class="o">()</span> <span class="o">?</span> <span class="n">promise</span><span class="o">.</span><span class="na">getNow</span><span class="o">()</span> <span class="o">:</span> <span class="n">promise</span><span class="o">.</span><span class="na">cause</span><span class="o">()).</span><span class="na">toString</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">eventExecutors</span><span class="o">.</span><span class="na">execute</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">Thread</span><span class="o">.</span><span class="na">sleep</span><span class="o">(</span><span class="n">1000</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">InterruptedException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="n">RuntimeException</span> <span class="n">e</span> <span class="o">=</span> <span class="k">new</span> <span class="n">RuntimeException</span><span class="o">(</span><span class="s">&#34;error...&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;set failure, {}&#34;</span><span class="o">,</span> <span class="n">e</span><span class="o">.</span><span class="na">toString</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">    <span class="n">promise</span><span class="o">.</span><span class="na">setFailure</span><span class="o">(</span><span class="n">e</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">&#34;start...&#34;</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">12:04:57 [DEBUG] [main] c.i.o.DefaultPromiseTest2 - start...
</span></span><span class="line"><span class="cl">12:04:58 [DEBUG] [defaultEventLoop-1-1] c.i.o.DefaultPromiseTest2 - set failure, java.lang.RuntimeException: error...
</span></span><span class="line"><span class="cl">12:04:58 [DEBUG] [defaultEventLoop-1-1] c.i.o.DefaultPromiseTest2 - result java.lang.RuntimeException: error...
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="例6">例6</h4>
<p>await 死锁检查</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">DefaultEventLoop</span> <span class="n">eventExecutors</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultEventLoop</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">DefaultPromise</span><span class="o">&lt;</span><span class="n">Integer</span><span class="o">&gt;</span> <span class="n">promise</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DefaultPromise</span><span class="o">&lt;&gt;(</span><span class="n">eventExecutors</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">eventExecutors</span><span class="o">.</span><span class="na">submit</span><span class="o">(()-&gt;{</span>
</span></span><span class="line"><span class="cl">    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;1&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">promise</span><span class="o">.</span><span class="na">await</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">        <span class="c1">// 注意不能仅捕获 InterruptedException 异常
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>        <span class="c1">// 否则 死锁检查抛出的 BlockingOperationException 会继续向上传播
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>        <span class="c1">// 而提交的任务会被包装为 PromiseTask，它的 run 方法中会 catch 所有异常然后设置为 Promise 的失败结果而不会抛出
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span> 
</span></span><span class="line"><span class="cl">        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;2&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span><span class="line"><span class="cl"><span class="n">eventExecutors</span><span class="o">.</span><span class="na">submit</span><span class="o">(()-&gt;{</span>
</span></span><span class="line"><span class="cl">    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;3&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">promise</span><span class="o">.</span><span class="na">await</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;4&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">1
</span></span><span class="line"><span class="cl">2
</span></span><span class="line"><span class="cl">3
</span></span><span class="line"><span class="cl">4
</span></span><span class="line"><span class="cl">io.netty.util.concurrent.BlockingOperationException: DefaultPromise@47499c2a(incomplete)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.DefaultPromise.checkDeadLock(DefaultPromise.java:384)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.DefaultPromise.await(DefaultPromise.java:212)
</span></span><span class="line"><span class="cl">	at com.itcast.oio.DefaultPromiseTest.lambda$main$0(DefaultPromiseTest.java:27)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.PromiseTask$RunnableAdapter.call(PromiseTask.java:38)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.PromiseTask.run(PromiseTask.java:73)
</span></span><span class="line"><span class="cl">	at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:918)
</span></span><span class="line"><span class="cl">	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
</span></span><span class="line"><span class="cl">	at java.lang.Thread.run(Thread.java:745)
</span></span><span class="line"><span class="cl">io.netty.util.concurrent.BlockingOperationException: DefaultPromise@47499c2a(incomplete)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.DefaultPromise.checkDeadLock(DefaultPromise.java:384)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.DefaultPromise.await(DefaultPromise.java:212)
</span></span><span class="line"><span class="cl">	at com.itcast.oio.DefaultPromiseTest.lambda$main$1(DefaultPromiseTest.java:36)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.PromiseTask$RunnableAdapter.call(PromiseTask.java:38)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.PromiseTask.run(PromiseTask.java:73)
</span></span><span class="line"><span class="cl">	at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:918)
</span></span><span class="line"><span class="cl">	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
</span></span><span class="line"><span class="cl">	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
</span></span><span class="line"><span class="cl">	at java.lang.Thread.run(Thread.java:745)
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="34-handler--pipeline">3.4 Handler &amp; Pipeline</h3>
<p>ChannelHandler 用来处理 Channel 上的各种事件，分为入站、出站两种。所有 ChannelHandler 被连成一串，就是 Pipeline</p>
<ul>
<li>入站处理器通常是 ChannelInboundHandlerAdapter 的子类，主要用来读取客户端数据，写回结果</li>
<li>出站处理器通常是 ChannelOutboundHandlerAdapter 的子类，主要对写回结果进行加工</li>
</ul>
<p>打个比喻，每个 Channel 是一个产品的加工车间，Pipeline 是车间中的流水线，ChannelHandler 就是流水线上的各道工序，而后面要讲的 ByteBuf 是原材料，经过很多工序的加工：先经过一道道入站工序，再经过一道道出站工序最终变成产品</p>
<p>先搞清楚顺序，服务端</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="k">new</span> <span class="n">ServerBootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioServerSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">childHandler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">NioSocketChannel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">NioSocketChannel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInboundHandlerAdapter</span><span class="o">(){</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">channelRead</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">1</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ctx</span><span class="o">.</span><span class="na">fireChannelRead</span><span class="o">(</span><span class="n">msg</span><span class="o">);</span> <span class="c1">// 1
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInboundHandlerAdapter</span><span class="o">(){</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">channelRead</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">2</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ctx</span><span class="o">.</span><span class="na">fireChannelRead</span><span class="o">(</span><span class="n">msg</span><span class="o">);</span> <span class="c1">// 2
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInboundHandlerAdapter</span><span class="o">(){</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">channelRead</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">3</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ctx</span><span class="o">.</span><span class="na">channel</span><span class="o">().</span><span class="na">write</span><span class="o">(</span><span class="n">msg</span><span class="o">);</span> <span class="c1">// 3
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelOutboundHandlerAdapter</span><span class="o">(){</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">write</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">,</span> 
</span></span><span class="line"><span class="cl">                                  <span class="n">ChannelPromise</span> <span class="n">promise</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">4</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ctx</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="n">msg</span><span class="o">,</span> <span class="n">promise</span><span class="o">);</span> <span class="c1">// 4
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelOutboundHandlerAdapter</span><span class="o">(){</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">write</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">,</span> 
</span></span><span class="line"><span class="cl">                                  <span class="n">ChannelPromise</span> <span class="n">promise</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">5</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ctx</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="n">msg</span><span class="o">,</span> <span class="n">promise</span><span class="o">);</span> <span class="c1">// 5
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelOutboundHandlerAdapter</span><span class="o">(){</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">write</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">,</span> 
</span></span><span class="line"><span class="cl">                                  <span class="n">ChannelPromise</span> <span class="n">promise</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">6</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ctx</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="n">msg</span><span class="o">,</span> <span class="n">promise</span><span class="o">);</span> <span class="c1">// 6
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">})</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">bind</span><span class="o">(</span><span class="n">8080</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>客户端</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="k">new</span> <span class="n">Bootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">handler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">Channel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">Channel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">StringEncoder</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">})</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">connect</span><span class="o">(</span><span class="s">&#34;127.0.0.1&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">addListener</span><span class="o">((</span><span class="n">ChannelFutureListener</span><span class="o">)</span> <span class="n">future</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">future</span><span class="o">.</span><span class="na">channel</span><span class="o">().</span><span class="na">writeAndFlush</span><span class="o">(</span><span class="s">&#34;hello,world&#34;</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">});</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>服务器端打印：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">1
</span></span><span class="line"><span class="cl">2
</span></span><span class="line"><span class="cl">3
</span></span><span class="line"><span class="cl">6
</span></span><span class="line"><span class="cl">5
</span></span><span class="line"><span class="cl">4
</span></span></code></pre></td></tr></table>
</div>
</div><p>可以看到，ChannelInboundHandlerAdapter 是按照 addLast 的顺序执行的，而 ChannelOutboundHandlerAdapter 是按照 addLast 的逆序执行的。ChannelPipeline 的实现是一个 ChannelHandlerContext（包装了 ChannelHandler） 组成的双向链表</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0008.png"
        data-srcset="/img/0008.png, /img/0008.png 1.5x, /img/0008.png 2x"
        data-sizes="auto"
        alt="/img/0008.png"
        title="/img/0008.png" /></p>
<ul>
<li>入站处理器中，ctx.fireChannelRead(msg) 是 <strong>调用下一个入站处理器</strong>
<ul>
<li>如果注释掉 1 处代码，则仅会打印 1</li>
<li>如果注释掉 2 处代码，则仅会打印 1 2</li>
</ul>
</li>
<li>3 处的 ctx.channel().write(msg) 会 <strong>从尾部开始触发</strong> 后续出站处理器的执行
<ul>
<li>如果注释掉 3 处代码，则仅会打印 1 2 3</li>
</ul>
</li>
<li>类似的，出站处理器中，ctx.write(msg, promise) 的调用也会 <strong>触发上一个出站处理器</strong>
<ul>
<li>如果注释掉 6 处代码，则仅会打印 1 2 3 6</li>
</ul>
</li>
<li>ctx.channel().write(msg) vs ctx.write(msg)
<ul>
<li>都是触发出站处理器的执行</li>
<li>ctx.channel().write(msg) 从尾部开始查找出站处理器</li>
<li>ctx.write(msg) 是从当前节点找上一个出站处理器</li>
<li>3 处的 ctx.channel().write(msg) 如果改为 ctx.write(msg) 仅会打印 1 2 3，因为节点3 之前没有其它出站处理器了</li>
<li>6 处的 ctx.write(msg, promise) 如果改为 ctx.channel().write(msg) 会打印 1 2 3 6 6 6&hellip; 因为 ctx.channel().write() 是从尾部开始查找，结果又是节点6 自己</li>
</ul>
</li>
</ul>
<p>图1 - 服务端 pipeline 触发的原始流程，图中数字代表了处理步骤的先后次序</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0009.png"
        data-srcset="/img/0009.png, /img/0009.png 1.5x, /img/0009.png 2x"
        data-sizes="auto"
        alt="/img/0009.png"
        title="/img/0009.png" /></p>
<h3 id="35-bytebuf">3.5 ByteBuf</h3>
<p>是对字节数据的封装</p>
<h4 id="1创建">1）创建</h4>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buffer</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">buffer</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">(</span><span class="n">buffer</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>上面代码创建了一个默认的 ByteBuf（池化基于直接内存的 ByteBuf），初始容量是 10</p>
<p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">read index:0 write index:0 capacity:10
</span></span></code></pre></td></tr></table>
</div>
</div><p>其中 log 方法参考如下</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">private</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="n">ByteBuf</span> <span class="n">buffer</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="kt">int</span> <span class="n">length</span> <span class="o">=</span> <span class="n">buffer</span><span class="o">.</span><span class="na">readableBytes</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="kt">int</span> <span class="n">rows</span> <span class="o">=</span> <span class="n">length</span> <span class="o">/</span> <span class="n">16</span> <span class="o">+</span> <span class="o">(</span><span class="n">length</span> <span class="o">%</span> <span class="n">15</span> <span class="o">==</span> <span class="n">0</span> <span class="o">?</span> <span class="n">0</span> <span class="o">:</span> <span class="n">1</span><span class="o">)</span> <span class="o">+</span> <span class="n">4</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">    <span class="n">StringBuilder</span> <span class="n">buf</span> <span class="o">=</span> <span class="k">new</span> <span class="n">StringBuilder</span><span class="o">(</span><span class="n">rows</span> <span class="o">*</span> <span class="n">80</span> <span class="o">*</span> <span class="n">2</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">        <span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">&#34;read index:&#34;</span><span class="o">).</span><span class="na">append</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">readerIndex</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">        <span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">&#34; write index:&#34;</span><span class="o">).</span><span class="na">append</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">writerIndex</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">        <span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="s">&#34; capacity:&#34;</span><span class="o">).</span><span class="na">append</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">capacity</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">        <span class="o">.</span><span class="na">append</span><span class="o">(</span><span class="n">NEWLINE</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="n">appendPrettyHexDump</span><span class="o">(</span><span class="n">buf</span><span class="o">,</span> <span class="n">buffer</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">buf</span><span class="o">.</span><span class="na">toString</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="2直接内存-vs-堆内存">2）直接内存 vs 堆内存</h4>
<p>可以使用下面的代码来创建池化基于堆的 ByteBuf</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buffer</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">heapBuffer</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>也可以使用下面的代码来创建池化基于直接内存的 ByteBuf</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buffer</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">directBuffer</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>直接内存创建和销毁的代价昂贵，但读写性能高（少一次内存复制），适合配合池化功能一起用</li>
<li>直接内存对 GC 压力小，因为这部分内存不受 JVM 垃圾回收的管理，但也要注意及时主动释放</li>
</ul>
<h4 id="3池化-vs-非池化">3）池化 vs 非池化</h4>
<p>池化的最大意义在于可以重用 ByteBuf，优点有</p>
<ul>
<li>没有池化，则每次都得创建新的 ByteBuf 实例，这个操作对直接内存代价昂贵，就算是堆内存，也会增加 GC 压力</li>
<li>有了池化，则可以重用池中 ByteBuf 实例，并且采用了与 jemalloc 类似的内存分配算法提升分配效率</li>
<li>高并发时，池化功能更节约内存，减少内存溢出的可能</li>
</ul>
<p>池化功能是否开启，可以通过下面的系统环境变量来设置</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="o">-</span><span class="n">Dio</span><span class="o">.</span><span class="na">netty</span><span class="o">.</span><span class="na">allocator</span><span class="o">.</span><span class="na">type</span><span class="o">={</span><span class="n">unpooled</span><span class="o">|</span><span class="n">pooled</span><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>4.1 以后，非 Android 平台默认启用池化实现，Android 平台启用非池化实现</li>
<li>4.1 之前，池化功能还不成熟，默认是非池化实现</li>
</ul>
<h4 id="4组成">4）组成</h4>
<p>ByteBuf 由四部分组成</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0010.png"
        data-srcset="/img/0010.png, /img/0010.png 1.5x, /img/0010.png 2x"
        data-sizes="auto"
        alt="/img/0010.png"
        title="/img/0010.png" /></p>
<p>最开始读写指针都在 0 位置</p>
<h4 id="5写入">5）写入</h4>
<p>方法列表，省略一些不重要的方法</p>
<table>
<thead>
<tr>
<th>方法签名</th>
<th>含义</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>writeBoolean(boolean value)</td>
<td>写入 boolean 值</td>
<td>用一字节 01|00 代表 true|false</td>
</tr>
<tr>
<td>writeByte(int value)</td>
<td>写入 byte 值</td>
<td></td>
</tr>
<tr>
<td>writeShort(int value)</td>
<td>写入 short 值</td>
<td></td>
</tr>
<tr>
<td>writeInt(int value)</td>
<td>写入 int 值</td>
<td>Big Endian，即 0x250，写入后 00 00 02 50</td>
</tr>
<tr>
<td>writeIntLE(int value)</td>
<td>写入 int 值</td>
<td>Little Endian，即 0x250，写入后 50 02 00 00</td>
</tr>
<tr>
<td>writeLong(long value)</td>
<td>写入 long 值</td>
<td></td>
</tr>
<tr>
<td>writeChar(int value)</td>
<td>写入 char 值</td>
<td></td>
</tr>
<tr>
<td>writeFloat(float value)</td>
<td>写入 float 值</td>
<td></td>
</tr>
<tr>
<td>writeDouble(double value)</td>
<td>写入 double 值</td>
<td></td>
</tr>
<tr>
<td>writeBytes(ByteBuf src)</td>
<td>写入 netty 的 ByteBuf</td>
<td></td>
</tr>
<tr>
<td>writeBytes(byte[] src)</td>
<td>写入 byte[]</td>
<td></td>
</tr>
<tr>
<td>writeBytes(ByteBuffer src)</td>
<td>写入 nio 的 ByteBuffer</td>
<td></td>
</tr>
<tr>
<td>int writeCharSequence(CharSequence sequence, Charset charset)</td>
<td>写入字符串</td>
<td></td>
</tr>
</tbody>
</table>
<blockquote>
<p>注意</p>
<ul>
<li>这些方法的未指明返回值的，其返回值都是 ByteBuf，意味着可以链式调用</li>
<li>网络传输，默认习惯是 Big Endian</li>
</ul>
</blockquote>
<p>先写入 4 个字节</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">buffer</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="k">new</span> <span class="kt">byte</span><span class="o">[]{</span><span class="n">1</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">4</span><span class="o">});</span>
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">(</span><span class="n">buffer</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>结果是</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">read index:0 write index:4 capacity:10
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 01 02 03 04                                     |....            |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>再写入一个 int 整数，也是 4 个字节</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">buffer</span><span class="o">.</span><span class="na">writeInt</span><span class="o">(</span><span class="n">5</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">(</span><span class="n">buffer</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>结果是</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">read index:0 write index:8 capacity:10
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 01 02 03 04 00 00 00 05                         |........        |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>还有一类方法是 set 开头的一系列方法，也可以写入数据，但不会改变写指针位置</p>
<h4 id="6扩容">6）扩容</h4>
<p>再写入一个 int 整数时，容量不够了（初始容量是 10），这时会引发扩容</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">buffer</span><span class="o">.</span><span class="na">writeInt</span><span class="o">(</span><span class="n">6</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">(</span><span class="n">buffer</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>扩容规则是</p>
<ul>
<li>如何写入后数据大小未超过 512，则选择下一个 16 的整数倍，例如写入后大小为 12 ，则扩容后 capacity 是 16</li>
<li>如果写入后数据大小超过 512，则选择下一个 2^n，例如写入后大小为 513，则扩容后 capacity 是 2^10=1024（2^9=512 已经不够了）</li>
<li>扩容不能超过 max capacity 会报错</li>
</ul>
<p>结果是</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">read index:0 write index:12 capacity:16
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 01 02 03 04 00 00 00 05 00 00 00 06             |............    |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="7读取">7）读取</h4>
<p>例如读了 4 次，每次一个字节</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">readByte</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">readByte</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">readByte</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">readByte</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">(</span><span class="n">buffer</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>读过的内容，就属于废弃部分了，再读只能读那些尚未读取的部分</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">1
</span></span><span class="line"><span class="cl">2
</span></span><span class="line"><span class="cl">3
</span></span><span class="line"><span class="cl">4
</span></span><span class="line"><span class="cl">read index:4 write index:12 capacity:16
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 00 00 00 05 00 00 00 06                         |........        |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>如果需要重复读取 int 整数 5，怎么办？</p>
<p>可以在 read 前先做个标记 mark</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">buffer</span><span class="o">.</span><span class="na">markReaderIndex</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">readInt</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">(</span><span class="n">buffer</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>结果</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">5
</span></span><span class="line"><span class="cl">read index:8 write index:12 capacity:16
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 00 00 00 06                                     |....            |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>这时要重复读取的话，重置到标记位置 reset</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">buffer</span><span class="o">.</span><span class="na">resetReaderIndex</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">log</span><span class="o">(</span><span class="n">buffer</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>这时</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">read index:4 write index:12 capacity:16
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 00 00 00 05 00 00 00 06                         |........        |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>还有种办法是采用 get 开头的一系列方法，这些方法不会改变 read index</p>
<h4 id="8retain--release">8）retain &amp; release</h4>
<p>由于 Netty 中有堆外内存的 ByteBuf 实现，堆外内存最好是手动来释放，而不是等 GC 垃圾回收。</p>
<ul>
<li>UnpooledHeapByteBuf 使用的是 JVM 内存，只需等 GC 回收内存即可</li>
<li>UnpooledDirectByteBuf 使用的就是直接内存了，需要特殊的方法来回收内存</li>
<li>PooledByteBuf 和它的子类使用了池化机制，需要更复杂的规则来回收内存</li>
</ul>
<blockquote>
<p>回收内存的源码实现，请关注下面方法的不同实现</p>
<p><code>protected abstract void deallocate()</code></p>
</blockquote>
<p>Netty 这里采用了引用计数法来控制回收内存，每个 ByteBuf 都实现了 ReferenceCounted 接口</p>
<ul>
<li>每个 ByteBuf 对象的初始计数为 1</li>
<li>调用 release 方法计数减 1，如果计数为 0，ByteBuf 内存被回收</li>
<li>调用 retain 方法计数加 1，表示调用者没用完之前，其它 handler 即使调用了 release 也不会造成回收</li>
<li>当计数为 0 时，底层内存会被回收，这时即使 ByteBuf 对象还在，其各个方法均无法正常使用</li>
</ul>
<p>谁来负责 release 呢？</p>
<p>不是我们想象的（一般情况下）</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buf</span> <span class="o">=</span> <span class="o">...</span>
</span></span><span class="line"><span class="cl"><span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="o">...</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">buf</span><span class="o">.</span><span class="na">release</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>请思考，因为 pipeline 的存在，一般需要将 ByteBuf 传递给下一个 ChannelHandler，如果在 finally 中 release 了，就失去了传递性（当然，如果在这个 ChannelHandler 内这个 ByteBuf 已完成了它的使命，那么便无须再传递）</p>
<p>基本规则是，<strong>谁是最后使用者，谁负责 release</strong>，详细分析如下</p>
<ul>
<li>起点，对于 NIO 实现来讲，在 io.netty.channel.nio.AbstractNioByteChannel.NioByteUnsafe#read 方法中首次创建 ByteBuf 放入 pipeline（line 163 pipeline.fireChannelRead(byteBuf)）</li>
<li>入站 ByteBuf 处理原则
<ul>
<li>对原始 ByteBuf 不做处理，调用 ctx.fireChannelRead(msg) 向后传递，这时无须 release</li>
<li>将原始 ByteBuf 转换为其它类型的 Java 对象，这时 ByteBuf 就没用了，必须 release</li>
<li>如果不调用 ctx.fireChannelRead(msg) 向后传递，那么也必须 release</li>
<li>注意各种异常，如果 ByteBuf 没有成功传递到下一个 ChannelHandler，必须 release</li>
<li>假设消息一直向后传，那么 TailContext 会负责释放未处理消息（原始的 ByteBuf）</li>
</ul>
</li>
<li>出站 ByteBuf 处理原则
<ul>
<li>出站消息最终都会转为 ByteBuf 输出，一直向前传，由 HeadContext flush 后 release</li>
</ul>
</li>
<li>异常处理原则
<ul>
<li>有时候不清楚 ByteBuf 被引用了多少次，但又必须彻底释放，可以循环调用 release 直到返回 true</li>
</ul>
</li>
</ul>
<p>TailContext 释放未处理消息逻辑</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="c1">// io.netty.channel.DefaultChannelPipeline#onUnhandledInboundMessage(java.lang.Object)
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">protected</span> <span class="kt">void</span> <span class="nf">onUnhandledInboundMessage</span><span class="o">(</span><span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">logger</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span>
</span></span><span class="line"><span class="cl">            <span class="s">&#34;Discarded inbound message {} that reached at the tail of the pipeline. &#34;</span> <span class="o">+</span>
</span></span><span class="line"><span class="cl">            <span class="s">&#34;Please check your pipeline configuration.&#34;</span><span class="o">,</span> <span class="n">msg</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">ReferenceCountUtil</span><span class="o">.</span><span class="na">release</span><span class="o">(</span><span class="n">msg</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>具体代码</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="c1">// io.netty.util.ReferenceCountUtil#release(java.lang.Object)
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">public</span> <span class="kd">static</span> <span class="kt">boolean</span> <span class="nf">release</span><span class="o">(</span><span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="o">(</span><span class="n">msg</span> <span class="k">instanceof</span> <span class="n">ReferenceCounted</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="o">((</span><span class="n">ReferenceCounted</span><span class="o">)</span> <span class="n">msg</span><span class="o">).</span><span class="na">release</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="kc">false</span><span class="o">;</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="9slice">9）slice</h4>
<p>【零拷贝】的体现之一，对原始 ByteBuf 进行切片成多个 ByteBuf，切片后的 ByteBuf 并没有发生内存复制，还是使用原始 ByteBuf 的内存，切片后的 ByteBuf 维护独立的 read，write 指针</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0011.png"
        data-srcset="/img/0011.png, /img/0011.png 1.5x, /img/0011.png 2x"
        data-sizes="auto"
        alt="/img/0011.png"
        title="/img/0011.png" /></p>
<p>例，原始 ByteBuf 进行一些初始操作</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">origin</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">buffer</span><span class="o">(</span><span class="n">10</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">origin</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="k">new</span> <span class="kt">byte</span><span class="o">[]{</span><span class="n">1</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">4</span><span class="o">});</span>
</span></span><span class="line"><span class="cl"><span class="n">origin</span><span class="o">.</span><span class="na">readByte</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">origin</span><span class="o">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 02 03 04                                        |...             |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>这时调用 slice 进行切片，无参 slice 是从原始 ByteBuf 的 read index 到 write index 之间的内容进行切片，切片后的 max capacity 被固定为这个区间的大小，因此不能追加 write</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">slice</span> <span class="o">=</span> <span class="n">origin</span><span class="o">.</span><span class="na">slice</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">slice</span><span class="o">));</span>
</span></span><span class="line"><span class="cl"><span class="c1">// slice.writeByte(5); 如果执行，会报 IndexOutOfBoundsException 异常
</span></span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 02 03 04                                        |...             |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>如果原始 ByteBuf 再次读操作（又读了一个字节）</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">origin</span><span class="o">.</span><span class="na">readByte</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">origin</span><span class="o">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 03 04                                           |..              |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>这时的 slice 不受影响，因为它有独立的读写指针</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">slice</span><span class="o">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 02 03 04                                        |...             |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>如果 slice 的内容发生了更改</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">slice</span><span class="o">.</span><span class="na">setByte</span><span class="o">(</span><span class="n">2</span><span class="o">,</span> <span class="n">5</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">slice</span><span class="o">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 02 03 05                                        |...             |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>这时，原始 ByteBuf 也会受影响，因为底层都是同一块内存</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">System.out.println(ByteBufUtil.prettyHexDump(origin));
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 03 05                                           |..              |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="10duplicate">10）duplicate</h4>
<p>【零拷贝】的体现之一，就好比截取了原始 ByteBuf 所有内容，并且没有 max capacity 的限制，也是与原始 ByteBuf 使用同一块底层内存，只是读写指针是独立的</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="/img/0012.png"
        data-srcset="/img/0012.png, /img/0012.png 1.5x, /img/0012.png 2x"
        data-sizes="auto"
        alt="/img/0012.png"
        title="/img/0012.png" /></p>
<h4 id="11copy">11）copy</h4>
<p>会将底层内存数据进行深拷贝，因此无论读写，都与原始 ByteBuf 无关</p>
<h4 id="12compositebytebuf">12）CompositeByteBuf</h4>
<p>【零拷贝】的体现之一，可以将多个 ByteBuf 合并为一个逻辑上的 ByteBuf，避免拷贝</p>
<p>有两个 ByteBuf 如下</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buf1</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">buffer</span><span class="o">(</span><span class="n">5</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">buf1</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="k">new</span> <span class="kt">byte</span><span class="o">[]{</span><span class="n">1</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">5</span><span class="o">});</span>
</span></span><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buf2</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">buffer</span><span class="o">(</span><span class="n">5</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">buf2</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="k">new</span> <span class="kt">byte</span><span class="o">[]{</span><span class="n">6</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">8</span><span class="o">,</span> <span class="n">9</span><span class="o">,</span> <span class="n">10</span><span class="o">});</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">buf1</span><span class="o">));</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">buf2</span><span class="o">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 01 02 03 04 05                                  |.....           |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 06 07 08 09 0a                                  |.....           |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>现在需要一个新的 ByteBuf，内容来自于刚才的 buf1 和 buf2，如何实现？</p>
<p>方法1：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buf3</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">buffer</span><span class="o">(</span><span class="n">buf1</span><span class="o">.</span><span class="na">readableBytes</span><span class="o">()+</span><span class="n">buf2</span><span class="o">.</span><span class="na">readableBytes</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">buf3</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="n">buf1</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">buf3</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="n">buf2</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">buf3</span><span class="o">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>结果</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 01 02 03 04 05 06 07 08 09 0a                   |..........      |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>这种方法好不好？回答是不太好，因为进行了数据的内存复制操作</p>
<p>方法2：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">CompositeByteBuf</span> <span class="n">buf3</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">compositeBuffer</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="c1">// true 表示增加新的 ByteBuf 自动递增 write index, 否则 write index 会始终为 0
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">buf3</span><span class="o">.</span><span class="na">addComponents</span><span class="o">(</span><span class="kc">true</span><span class="o">,</span> <span class="n">buf1</span><span class="o">,</span> <span class="n">buf2</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>结果是一样的</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 01 02 03 04 05 06 07 08 09 0a                   |..........      |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>CompositeByteBuf 是一个组合的 ByteBuf，它内部维护了一个 Component 数组，每个 Component 管理一个 ByteBuf，记录了这个 ByteBuf 相对于整体偏移量等信息，代表着整体中某一段的数据。</p>
<ul>
<li>优点，对外是一个虚拟视图，组合这些 ByteBuf 不会产生内存复制</li>
<li>缺点，复杂了很多，多次操作会带来性能的损耗</li>
</ul>
<h4 id="13unpooled">13）Unpooled</h4>
<p>Unpooled 是一个工具类，类如其名，提供了非池化的 ByteBuf 创建、组合、复制等操作</p>
<p>这里仅介绍其跟【零拷贝】相关的 wrappedBuffer 方法，可以用来包装 ByteBuf</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buf1</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">buffer</span><span class="o">(</span><span class="n">5</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">buf1</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="k">new</span> <span class="kt">byte</span><span class="o">[]{</span><span class="n">1</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">3</span><span class="o">,</span> <span class="n">4</span><span class="o">,</span> <span class="n">5</span><span class="o">});</span>
</span></span><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buf2</span> <span class="o">=</span> <span class="n">ByteBufAllocator</span><span class="o">.</span><span class="na">DEFAULT</span><span class="o">.</span><span class="na">buffer</span><span class="o">(</span><span class="n">5</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">buf2</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="k">new</span> <span class="kt">byte</span><span class="o">[]{</span><span class="n">6</span><span class="o">,</span> <span class="n">7</span><span class="o">,</span> <span class="n">8</span><span class="o">,</span> <span class="n">9</span><span class="o">,</span> <span class="n">10</span><span class="o">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 当包装 ByteBuf 个数超过一个时, 底层使用了 CompositeByteBuf
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">ByteBuf</span> <span class="n">buf3</span> <span class="o">=</span> <span class="n">Unpooled</span><span class="o">.</span><span class="na">wrappedBuffer</span><span class="o">(</span><span class="n">buf1</span><span class="o">,</span> <span class="n">buf2</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">buf3</span><span class="o">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 01 02 03 04 05 06 07 08 09 0a                   |..........      |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><p>也可以用来包装普通字节数组，底层也不会有拷贝操作</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ByteBuf</span> <span class="n">buf4</span> <span class="o">=</span> <span class="n">Unpooled</span><span class="o">.</span><span class="na">wrappedBuffer</span><span class="o">(</span><span class="k">new</span> <span class="kt">byte</span><span class="o">[]{</span><span class="n">1</span><span class="o">,</span> <span class="n">2</span><span class="o">,</span> <span class="n">3</span><span class="o">},</span> <span class="k">new</span> <span class="kt">byte</span><span class="o">[]{</span><span class="n">4</span><span class="o">,</span> <span class="n">5</span><span class="o">,</span> <span class="n">6</span><span class="o">});</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">buf4</span><span class="o">.</span><span class="na">getClass</span><span class="o">());</span>
</span></span><span class="line"><span class="cl"><span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">ByteBufUtil</span><span class="o">.</span><span class="na">prettyHexDump</span><span class="o">(</span><span class="n">buf4</span><span class="o">));</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>输出</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">class io.netty.buffer.CompositeByteBuf
</span></span><span class="line"><span class="cl">         +-------------------------------------------------+
</span></span><span class="line"><span class="cl">         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span><span class="line"><span class="cl">|00000000| 01 02 03 04 05 06                               |......          |
</span></span><span class="line"><span class="cl">+--------+-------------------------------------------------+----------------+
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="-bytebuf-优势">💡 ByteBuf 优势</h4>
<ul>
<li>池化 - 可以重用池中 ByteBuf 实例，更节约内存，减少内存溢出的可能</li>
<li>读写指针分离，不需要像 ByteBuffer 一样切换读写模式</li>
<li>可以自动扩容</li>
<li>支持链式调用，使用更流畅</li>
<li>很多地方体现零拷贝，例如 slice、duplicate、CompositeByteBuf</li>
</ul>
<h2 id="4-双向通信">4. 双向通信</h2>
<h3 id="41-练习">4.1 练习</h3>
<p>实现一个 echo server</p>
<p>编写 server</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="k">new</span> <span class="n">ServerBootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">())</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioServerSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">childHandler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">NioSocketChannel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">NioSocketChannel</span> <span class="n">ch</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInboundHandlerAdapter</span><span class="o">(){</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">channelRead</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ByteBuf</span> <span class="n">buffer</span> <span class="o">=</span> <span class="o">(</span><span class="n">ByteBuf</span><span class="o">)</span> <span class="n">msg</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">Charset</span><span class="o">.</span><span class="na">defaultCharset</span><span class="o">()));</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">                    <span class="c1">// 建议使用 ctx.alloc() 创建 ByteBuf
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                    <span class="n">ByteBuf</span> <span class="n">response</span> <span class="o">=</span> <span class="n">ctx</span><span class="o">.</span><span class="na">alloc</span><span class="o">().</span><span class="na">buffer</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">                    <span class="n">response</span><span class="o">.</span><span class="na">writeBytes</span><span class="o">(</span><span class="n">buffer</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ctx</span><span class="o">.</span><span class="na">writeAndFlush</span><span class="o">(</span><span class="n">response</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">                    <span class="c1">// 思考：需要释放 buffer 吗
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                    <span class="c1">// 思考：需要释放 response 吗
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">}).</span><span class="na">bind</span><span class="o">(</span><span class="n">8080</span><span class="o">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>编写 client</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">NioEventLoopGroup</span> <span class="n">group</span> <span class="o">=</span> <span class="k">new</span> <span class="n">NioEventLoopGroup</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">Channel</span> <span class="n">channel</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Bootstrap</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">group</span><span class="o">(</span><span class="n">group</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">channel</span><span class="o">(</span><span class="n">NioSocketChannel</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="o">.</span><span class="na">handler</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInitializer</span><span class="o">&lt;</span><span class="n">NioSocketChannel</span><span class="o">&gt;()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">        <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">initChannel</span><span class="o">(</span><span class="n">NioSocketChannel</span> <span class="n">ch</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">StringEncoder</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">            <span class="n">ch</span><span class="o">.</span><span class="na">pipeline</span><span class="o">().</span><span class="na">addLast</span><span class="o">(</span><span class="k">new</span> <span class="n">ChannelInboundHandlerAdapter</span><span class="o">()</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="nd">@Override</span>
</span></span><span class="line"><span class="cl">                <span class="kd">public</span> <span class="kt">void</span> <span class="nf">channelRead</span><span class="o">(</span><span class="n">ChannelHandlerContext</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">Object</span> <span class="n">msg</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">ByteBuf</span> <span class="n">buffer</span> <span class="o">=</span> <span class="o">(</span><span class="n">ByteBuf</span><span class="o">)</span> <span class="n">msg</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">buffer</span><span class="o">.</span><span class="na">toString</span><span class="o">(</span><span class="n">Charset</span><span class="o">.</span><span class="na">defaultCharset</span><span class="o">()));</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">                    <span class="c1">// 思考：需要释放 buffer 吗
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">});</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">    <span class="o">}).</span><span class="na">connect</span><span class="o">(</span><span class="s">&#34;127.0.0.1&#34;</span><span class="o">,</span> <span class="n">8080</span><span class="o">).</span><span class="na">sync</span><span class="o">().</span><span class="na">channel</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">channel</span><span class="o">.</span><span class="na">closeFuture</span><span class="o">().</span><span class="na">addListener</span><span class="o">(</span><span class="n">future</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">group</span><span class="o">.</span><span class="na">shutdownGracefully</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="o">});</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">new</span> <span class="n">Thread</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">Scanner</span> <span class="n">scanner</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Scanner</span><span class="o">(</span><span class="n">System</span><span class="o">.</span><span class="na">in</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="k">while</span> <span class="o">(</span><span class="kc">true</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">String</span> <span class="n">line</span> <span class="o">=</span> <span class="n">scanner</span><span class="o">.</span><span class="na">nextLine</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="o">(</span><span class="s">&#34;q&#34;</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">line</span><span class="o">))</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="n">channel</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">            <span class="k">break</span><span class="o">;</span>
</span></span><span class="line"><span class="cl">        <span class="o">}</span>
</span></span><span class="line"><span class="cl">        <span class="n">channel</span><span class="o">.</span><span class="na">writeAndFlush</span><span class="o">(</span><span class="n">line</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}).</span><span class="na">start</span><span class="o">();</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="-读和写的误解">💡 读和写的误解</h3>
<p>我最初在认识上有这样的误区，认为只有在 netty，nio 这样的多路复用 IO 模型时，读写才不会相互阻塞，才可以实现高效的双向通信，但实际上，Java Socket 是全双工的：在任意时刻，线路上存在<code>A 到 B</code> 和 <code>B 到 A</code> 的双向信号传输。即使是阻塞 IO，读和写是可以同时进行的，只要分别采用读线程和写线程即可，读不会阻塞写、写也不会阻塞读</p>
<p>例如</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">TestServer</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">ServerSocket</span> <span class="n">ss</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ServerSocket</span><span class="o">(</span><span class="n">8888</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">        <span class="n">Socket</span> <span class="n">s</span> <span class="o">=</span> <span class="n">ss</span><span class="o">.</span><span class="na">accept</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">new</span> <span class="n">Thread</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">BufferedReader</span> <span class="n">reader</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="n">InputStreamReader</span><span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">getInputStream</span><span class="o">()));</span>
</span></span><span class="line"><span class="cl">                <span class="k">while</span> <span class="o">(</span><span class="kc">true</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">reader</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span>
</span></span><span class="line"><span class="cl">        <span class="o">}).</span><span class="na">start</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">new</span> <span class="n">Thread</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">BufferedWriter</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BufferedWriter</span><span class="o">(</span><span class="k">new</span> <span class="n">OutputStreamWriter</span><span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">getOutputStream</span><span class="o">()));</span>
</span></span><span class="line"><span class="cl">                <span class="c1">// 例如在这个位置加入 thread 级别断点，可以发现即使不写入数据，也不妨碍前面线程读取客户端数据
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">100</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">writer</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="n">String</span><span class="o">.</span><span class="na">valueOf</span><span class="o">(</span><span class="n">i</span><span class="o">));</span>
</span></span><span class="line"><span class="cl">                    <span class="n">writer</span><span class="o">.</span><span class="na">newLine</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">                    <span class="n">writer</span><span class="o">.</span><span class="na">flush</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span>
</span></span><span class="line"><span class="cl">        <span class="o">}).</span><span class="na">start</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>客户端</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">TestClient</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">Socket</span> <span class="n">s</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Socket</span><span class="o">(</span><span class="s">&#34;localhost&#34;</span><span class="o">,</span> <span class="n">8888</span><span class="o">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">new</span> <span class="n">Thread</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">BufferedReader</span> <span class="n">reader</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="n">InputStreamReader</span><span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">getInputStream</span><span class="o">()));</span>
</span></span><span class="line"><span class="cl">                <span class="k">while</span> <span class="o">(</span><span class="kc">true</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">reader</span><span class="o">.</span><span class="na">readLine</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span>
</span></span><span class="line"><span class="cl">        <span class="o">}).</span><span class="na">start</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">        <span class="k">new</span> <span class="n">Thread</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">            <span class="k">try</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">BufferedWriter</span> <span class="n">writer</span> <span class="o">=</span> <span class="k">new</span> <span class="n">BufferedWriter</span><span class="o">(</span><span class="k">new</span> <span class="n">OutputStreamWriter</span><span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">getOutputStream</span><span class="o">()));</span>
</span></span><span class="line"><span class="cl">                <span class="k">for</span> <span class="o">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">0</span><span class="o">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">100</span><span class="o">;</span> <span class="n">i</span><span class="o">++)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                    <span class="n">writer</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="n">String</span><span class="o">.</span><span class="na">valueOf</span><span class="o">(</span><span class="n">i</span><span class="o">));</span>
</span></span><span class="line"><span class="cl">                    <span class="n">writer</span><span class="o">.</span><span class="na">newLine</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">                    <span class="n">writer</span><span class="o">.</span><span class="na">flush</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">                <span class="o">}</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">                <span class="n">e</span><span class="o">.</span><span class="na">printStackTrace</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">            <span class="o">}</span>
</span></span><span class="line"><span class="cl">        <span class="o">}).</span><span class="na">start</span><span class="o">();</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div></div>

        <div id="donateDiv"><a id="donate">打赏</a></div>
<div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>更新于 2024-05-26</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/%E7%BD%91%E7%BB%9C/">网络</a>,&nbsp;<a href="/tags/netty/">Netty</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">返回</a></span>&nbsp;|&nbsp;<span><a href="/">主页</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/posts/network/netty01-nio/" class="prev" rel="prev" title="JAVA NIO"><i class="fas fa-angle-left fa-fw"></i>JAVA NIO</a>
            <a href="/posts/network/netty03-%E8%BF%9B%E9%98%B6/" class="next" rel="next" title="Netty 进阶">Netty 进阶<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
<div id="comments"><div id="valine" class="comment"></div><noscript>
                Please enable JavaScript to view the comments powered by <a href="https://valine.js.org/">Valine</a>.
            </noscript></div></article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.102.3">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2020 - 2024</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="https://wlizhi.cc" target="_blank">Wlizhi</a></span><span class="icp-splitter">&nbsp;|&nbsp;</span><br class="icp-br"/>
                    <span class="icp"><a href='https://beian.miit.gov.cn/' target='_blank'>豫ICP备17048163号<a/></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="查看评论">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><link rel="stylesheet" href="/lib/valine/valine.min.css"><link rel="stylesheet" href="/lib/lightgallery/lightgallery.min.css"><script type="text/javascript" src="/lib/valine/Valine.min.js"></script><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/autocomplete/autocomplete.min.js"></script><script type="text/javascript" src="/lib/algoliasearch/algoliasearch-lite.umd.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/lightgallery/lightgallery.min.js"></script><script type="text/javascript" src="/lib/lightgallery/lg-thumbnail.min.js"></script><script type="text/javascript" src="/lib/lightgallery/lg-zoom.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":35},"comment":{"valine":{"appId":"4yIHB0Rs1r3ykDVxayI5nqj3-gzGzoHsz","appKey":"ALr4H1hlK94girLDEUCGmp3o","avatar":"mp","el":"#valine","emojiCDN":"https://cdn.jsdelivr.net/npm/emoji-datasource-google@5.0.1/img/google/64/","emojiMaps":{"100":"1f4af.png","alien":"1f47d.png","anger":"1f4a2.png","angry":"1f620.png","anguished":"1f627.png","astonished":"1f632.png","black_heart":"1f5a4.png","blue_heart":"1f499.png","blush":"1f60a.png","bomb":"1f4a3.png","boom":"1f4a5.png","broken_heart":"1f494.png","brown_heart":"1f90e.png","clown_face":"1f921.png","cold_face":"1f976.png","cold_sweat":"1f630.png","confounded":"1f616.png","confused":"1f615.png","cry":"1f622.png","crying_cat_face":"1f63f.png","cupid":"1f498.png","dash":"1f4a8.png","disappointed":"1f61e.png","disappointed_relieved":"1f625.png","dizzy":"1f4ab.png","dizzy_face":"1f635.png","drooling_face":"1f924.png","exploding_head":"1f92f.png","expressionless":"1f611.png","face_vomiting":"1f92e.png","face_with_cowboy_hat":"1f920.png","face_with_hand_over_mouth":"1f92d.png","face_with_head_bandage":"1f915.png","face_with_monocle":"1f9d0.png","face_with_raised_eyebrow":"1f928.png","face_with_rolling_eyes":"1f644.png","face_with_symbols_on_mouth":"1f92c.png","face_with_thermometer":"1f912.png","fearful":"1f628.png","flushed":"1f633.png","frowning":"1f626.png","ghost":"1f47b.png","gift_heart":"1f49d.png","green_heart":"1f49a.png","grimacing":"1f62c.png","grin":"1f601.png","grinning":"1f600.png","hankey":"1f4a9.png","hear_no_evil":"1f649.png","heart":"2764-fe0f.png","heart_decoration":"1f49f.png","heart_eyes":"1f60d.png","heart_eyes_cat":"1f63b.png","heartbeat":"1f493.png","heartpulse":"1f497.png","heavy_heart_exclamation_mark_ornament":"2763-fe0f.png","hole":"1f573-fe0f.png","hot_face":"1f975.png","hugging_face":"1f917.png","hushed":"1f62f.png","imp":"1f47f.png","innocent":"1f607.png","japanese_goblin":"1f47a.png","japanese_ogre":"1f479.png","joy":"1f602.png","joy_cat":"1f639.png","kiss":"1f48b.png","kissing":"1f617.png","kissing_cat":"1f63d.png","kissing_closed_eyes":"1f61a.png","kissing_heart":"1f618.png","kissing_smiling_eyes":"1f619.png","laughing":"1f606.png","left_speech_bubble":"1f5e8-fe0f.png","love_letter":"1f48c.png","lying_face":"1f925.png","mask":"1f637.png","money_mouth_face":"1f911.png","nauseated_face":"1f922.png","nerd_face":"1f913.png","neutral_face":"1f610.png","no_mouth":"1f636.png","open_mouth":"1f62e.png","orange_heart":"1f9e1.png","partying_face":"1f973.png","pensive":"1f614.png","persevere":"1f623.png","pleading_face":"1f97a.png","pouting_cat":"1f63e.png","purple_heart":"1f49c.png","rage":"1f621.png","relaxed":"263a-fe0f.png","relieved":"1f60c.png","revolving_hearts":"1f49e.png","right_anger_bubble":"1f5ef-fe0f.png","robot_face":"1f916.png","rolling_on_the_floor_laughing":"1f923.png","scream":"1f631.png","scream_cat":"1f640.png","see_no_evil":"1f648.png","shushing_face":"1f92b.png","skull":"1f480.png","skull_and_crossbones":"2620-fe0f.png","sleeping":"1f634.png","sleepy":"1f62a.png","slightly_frowning_face":"1f641.png","slightly_smiling_face":"1f642.png","smile":"1f604.png","smile_cat":"1f638.png","smiley":"1f603.png","smiley_cat":"1f63a.png","smiling_face_with_3_hearts":"1f970.png","smiling_imp":"1f608.png","smirk":"1f60f.png","smirk_cat":"1f63c.png","sneezing_face":"1f927.png","sob":"1f62d.png","space_invader":"1f47e.png","sparkling_heart":"1f496.png","speak_no_evil":"1f64a.png","speech_balloon":"1f4ac.png","star-struck":"1f929.png","stuck_out_tongue":"1f61b.png","stuck_out_tongue_closed_eyes":"1f61d.png","stuck_out_tongue_winking_eye":"1f61c.png","sunglasses":"1f60e.png","sweat":"1f613.png","sweat_drops":"1f4a6.png","sweat_smile":"1f605.png","thinking_face":"1f914.png","thought_balloon":"1f4ad.png","tired_face":"1f62b.png","triumph":"1f624.png","two_hearts":"1f495.png","unamused":"1f612.png","upside_down_face":"1f643.png","weary":"1f629.png","white_frowning_face":"2639-fe0f.png","white_heart":"1f90d.png","wink":"1f609.png","woozy_face":"1f974.png","worried":"1f61f.png","yawning_face":"1f971.png","yellow_heart":"1f49b.png","yum":"1f60b.png","zany_face":"1f92a.png","zipper_mouth_face":"1f910.png","zzz":"1f4a4.png"},"enableQQ":true,"highlight":true,"lang":"zh-cn","meta":["nick","mail","link"],"pageSize":5,"placeholder":"昵称栏输入QQ，会使用QQ昵称和头像、并自动补充QQ邮箱到邮箱栏。\r\n正确填写邮箱更容易及时得到回复。\r\n说点什么吧...","recordIP":true,"visitor":true}},"lightGallery":{"actualSize":false,"exThumbImage":"data-thumbnail","hideBarsDelay":2000,"selector":".lightgallery","speed":400,"thumbContHeight":80,"thumbWidth":80,"thumbnail":true},"search":{"algoliaAppID":"1U459KF21F","algoliaIndex":"LoveItSite","algoliaSearchKey":"0433ffe95d71201a4f7c3e04b0125ac5","highlightTag":"em","maxResultLength":10,"noResultsFound":"没有找到结果","snippetLength":50,"type":"algolia"}};</script><script type="text/javascript" src="/js/theme.min.js"></script><script type="text/javascript" src="/js/donate.js"></script></body>
</html>
